为什么这个输出被打印出来,似乎不合适

时间:2013-03-06 23:38:39

标签: java

//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 正确。 干燥的越多,越潮湿越湿? 的不正确。再试一次。甚至在询问用户输入之前就会打印出来。

1 个答案:

答案 0 :(得分: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.");
    }
}

nextLine()之后,您必须始终nextInt()。新行未被nextInt()吞没,因此以下nextLine()吞噬了这个而不是您想要的内容。