制作Java程序循环直到输入x?

时间:2015-01-22 03:46:06

标签: java loops while-loop break

我想让我的程序循环,直到用户键入x而不是数字。我尝试使用while语句,但我不知道如何将它与多个变量一起使用。这是我的代码

public static void main(String[] args)
{
    int denominatorOne = 1, numeratorOne = 1;
    System.out.println("Welcome, type an \"x\" at any point to exit the program");
    while (numeratorOne !=x)
    {

        Scanner in = new Scanner(System.in);


        //Prompt the user for fraction one
        System.out.print("Enter the first numerator (top number): ");
        numeratorOne = in.nextInt();

        System.out.print("Enter the first denominator (bottom number): ");
        denominatorOne = in.nextInt();
    }
}

我的作业的确切措辞是The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)

4 个答案:

答案 0 :(得分:4)

首先,'x'不是一个数字,并且不会被nextInt接受或与'x'比较,你应该尝试检查它是否有下一个int(in.hasNextInt())并处理根据。除此之外,您还可以在while循环中轻松测试两个变量。假设您将变量设置为chars:

do {
    // scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))

答案 1 :(得分:1)

在这种情况下,你可以再次调用方法main();。

我建议的是创建一个新方法,在方法中只检查用户输入将输入作为字符串返回。然后你可以检查main方法中的字符串,如果那不是你想要的字符串,那么就回想一下这个方法。这是一个例子,请注意我没有使用IDE。

public String getMessage(){
Scanner input = System.in();
return input;
}

public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}

public static void main(String[] args){
checkMessage();
}

答案 2 :(得分:1)

你需要做的是拥有一个保存循环的bool值,以及何时在循环中检查keydown事件的if语句

bool looping = true

while(循环== true) {

if(按下x按钮== true)

{looping = false }

}

答案 3 :(得分:1)

尝试将其更改为

while(!numeratorOne.equals("x")){...}
相关问题