运行程序直到满足特定条件?

时间:2015-04-26 20:55:33

标签: java char user-input infinite-loop break

我希望此代码继续运行,只要用户在提示时继续输入“Y”或“y”,任何其他输入都应该退出程序。正如我的代码现在,无论输入什么,它只运行一次。我该如何解决?

这是我的代码:

import java.util.Scanner;

public class zigzag {
    public static void main(String[] args) {
        Scanner myScanner, sc;
        myScanner = new Scanner(System. in );

        while (true) {
            System.out.print("Enter an integer between 3 and 33: ");
            int nStars = myScanner.nextInt();

            if (nStars > 33 || nStars < 3) {
                System.out.println("Sorry, this input is out of the accepted range");
            } else {
                for (int i = 0; i < nStars; i++) {
                    System.out.print("*");
                }
                System.out.println(" ");
            }
            for (int j = 0; j < nStars - 2; j++) {
                System.out.print(" ");
                for (int k = 0; k <= j - 1; k++) {
                    System.out.print(" ");
                }
                System.out.println("*");
            }
            for (int g = 0; g < nStars; g++) {
                System.out.print("*");
            }
            System.out.println(" ");

            System.out.print("Enter 'Y' or 'y' to go again: ");
            char ch = myScanner.next().charAt(0);

            if (ch != 'y' || ch != 'Y') {
                break;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

你想要

if(ch!='y' && ch!='Y'){

if(ch!='y' || ch!='Y'){

答案 1 :(得分:1)

if (ch!='y' || ch!='Y') 

总是如此。

||更改为&&,使其看起来像:

if (ch!='y' && ch!='Y') 

答案 2 :(得分:0)

if条件错误 - 它将始终评估为true。由于某个角色不能同时为yY,因此始终为&#34;不等于y或不等于Y

相反,您需要一个条件来检查该字符是否不等于y 不等于Y

if( ch!='y' && ch!='Y') {
    break;
}
相关问题