所以我有一个并不复杂的方法,但它似乎是在我拥有的while循环中跳过2行代码。我尝试了一个Do-while和一个普通的while循环,这两个都没有帮助。这是代码:
do
{
System.out.println("Enter a building material that you would like to add :: ");
String first = keyboard.nextLine();
System.out.println("How many of that material would you like to add ::");
int second = keyboard.nextInt();
int i = (int)item.getID(first);
//long section of code here. It's not necessary
System.out.println("");
System.out.println("Lumber - " + lumber);
System.out.println("Plywood - " + plywood);
System.out.println("Cinderblocks - " + cinder);
System.out.println("Mortar - " + mortar);
System.out.println("Tank Traps - " + tanktrap);
System.out.println("Metal Poles - " + metalpole);
System.out.println("");
System.out.println("Would you like to add more materials? (yes / no) :: ");
String response = keyboard.next();
if(response.equalsIgnoreCase("yes"))
{
wantsNext = true;
}else{
wantsNext = false;
}
}while(wantsNext);
输出结果如下:
Welcome to OGx_Killer's Epoch Building Supplies Calculator
Enter a building material that you would like to add ::
cinderblock wall
How many of that material would you like to add ::
10
Lumber - 0
Plywood - 0
Cinderblocks - 70
Mortar - 20
Tank Traps - 0
Metal Poles - 0
Would you like to add more materials? (yes / no) ::
yes
Enter a building material that you would like to add ::
How many of that material would you like to add ::
正如你所看到的,第二次在循环中,它跳过第一个输入,留下第二个输入被回答,使循环无用。任何帮助将不胜感激。我感觉这是我正在使用的扫描仪方法的问题。它可能需要不是keyboard.nextLine()。非常感谢!
答案 0 :(得分:1)
<强>问题:强>
String first = keyboard.nextLine();
问题是它会消耗用户输入的keyboard.next();
的新行“\ n”,从而跳过它。
<强>溶液强>
改为使用next()
。
或强>
致电next()
致电nextLine()
以消费"\n"
<强>样品:强>
System.out.println("Would you like to add more materials? (yes / no) :: ");
String response = keyboard.next();
keyboard.nextLine();