【发布时间】:2022-12-04 07:49:03
【问题描述】:
此代码中的 for 循环在不接受输入的情况下运行一次。没有 do-while 循环和用户输入 shopList 数组长度,它运行没有问题。
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author cristian
*/
public class ShoppingList {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many items in this list?");
boolean okay;
do{
if (sc.hasNextDouble()) {
okay = true;
}else{
okay = false;
String word = sc.next(); //this may be the problem here
System.err.print( word + " is not a number\nTry again: ");
}
}while (!okay);
int l = sc.nextInt(); //the problem appeared the first time when I added this input
String[] shopList = new String[l]; //to give the length of this array
System.out.println("What do you want to buy?");
for (int x = 0 ; x < shopList.length; x++) { //this loop runs once without accepting input
System.out.print("Item: ");
String item = sc.nextLine();
if (item.equals("esc")) {
break;
}else{
shopList[x] = item;
//System.out.println(x);
}
}
System.out.println(Arrays.toString(shopList));
}
}
当我将“l”变量添加到数组长度以接受来自用户的输入时,问题首先出现。然后我将其注释掉并添加了一个 do-while 循环以确保长度的输入是一个数字,这又带来了另一个问题。
发生的情况是,当两者都没有被注释掉或者如果只注释掉 do-while 循环时,在我输入数组长度后,它打印出“Item:Item:”,它接受一个少的项目,最后它输出第一项就像我刚刚按下回车一样,没有写任何东西。 如果我只注释掉数组长度的输入,程序会在运行循环之前等待输入,并将其用于第一项。
我认为对于 do-while 循环,问题是“String word = sc.next();”但我不确定。至于数组长度输入,我不知道。有人可以帮忙吗?
【问题讨论】:
标签: java arrays loops user-input