所以我最近开始用 Java 编写代码,并且重写了我的第一个程序,试图通过使用方法使其更加优雅。这是我想到的:
import java.util.Scanner;
import java.util.ArrayList;
public class groceries {
static Scanner scan = new Scanner(System.in);
static ArrayList<String> shoppinglist = new ArrayList<>();
static int b = 0;
static String n ="";
public static void main(String[] args) {
getAmount(b);
getInput(b, n);
output();
}
private static void message (String m) {
System.out.println(m);
}
private static void getAmount(int b) {
message("How many articles do you want to buy?");
b = scan.nextInt();
}
private static void getInput(int b, String n) {
message("Which articles specifically do you want to buy?");
for (int i = 0; i <= b; i++) {
n = scan.nextLine();
shoppinglist.add(n);
}
}
private static void output() {
message("Here are your purchases:");
for (int k = 0; k<shoppinglist.size(); k++){
message(shoppinglist.get(k));
}
}
}
一切正常,直到我点击 getInput
- 我无法输入任何输入。程序结束并退出。
最佳答案
您之前正在调用方法nextInt()
。
问题是 nextInt() 不会消耗 '\n'
,因此下一次调用 nextLine()
会消耗它,然后等待读取输入“您具体想购买哪些商品?”。
您需要在调用 nextLine()
之前使用 '\n'
。
private static void getAmount(int b) {
message("How many articles do you want to buy?");
b = scan.nextInt();
scan.nextLine();// adding this, it will force to consume the '\n'
}
相关:Scanner is skipping nextLine() after using next() or nextFoo()?
关于java - For 循环不能在 Java 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60105449/