-1
//Question4 
correct = false;
System.out.println("how many feet are in a yard?");
while (!correct)
{
    x1 = input.nextInt();
    if (x1==3)
    {
        System.out.println("correct.");
        correct = true;
    }
    else
    {
        System.out.println("incorrect. try again.");
    }
}


    //Question5
correct = false;
System.out.println("What gets wetter and wetter the more it dries?");
while (correct == false)
{

   s1 = input.nextLine();
   if (s1.equalsIgnoreCase("a towel")) // cheating is bad!
    {
        System.out.println("correct");
        correct = true;
    }

    else
    {
        System.out.println("incorrect. try again.");
    }
}

输出 一码有多少英尺?3 正确。什么东西越干越湿? 不正确。再试一次。甚至在询问用户输入之前就被打印出来。

4

1 回答 1

1

像这样更改您的第一个问题:

while (!correct)
{
    x1 = input.nextInt();
    input.nextLine(); //NEW CODE
    if (x1==3)
    {
        System.out.println("correct.");
        correct = true;
    }
    else
    {
        System.out.println("incorrect. try again.");
    }
}

您必须始终在 anextLine()之后执行 a nextInt()。换行符尚未被吞入nextInt(),因此以下内容nextLine()正在吞下,而不是您想要的。

于 2013-03-06T23:41:41.337 回答