如何在Java中使用for循环和扫描程序添加数组
我对块底部的enterItemInfo()方法有问题。我希望用户输入一个项目名称,然后输入一个项目价格,并循环多次,循环次数等于项目名称。长我遇到的问题是,当我运行这个方法时,它以某种方式直接跳到第二个输入,然后任何给定的输入都会导致错误。我不知道我哪里出了问题
import java.util.Scanner;
public class Item {
//FIELDS
private int itemAmount;
private String[] itemNames;
private double[] itemPrices;
Scanner item = new Scanner(System.in);
public int getItemAmount() {
return this.itemAmount;
}
public void setItemAmount() {
System.out.println("Please enter the number of items: ");
this.itemAmount = item.nextInt();
System.out.print("There are " + this.itemAmount + " items.");
}
public void enterItemInfo() {
itemNames = new String[this.itemAmount];
for (int i = 0; i < itemNames.length; i++) {
System.out.println("Enter the next item name: ");
itemNames[i] = item.nextLine();
System.out.println("Enter the price for " + itemNames[i] + ": ");
itemPrices[i] = item.nextDouble();
item.nextLine();
}
}
}
# 1 楼答案
您错过了为itemprices数组创建对象。您的代码也跳过了输入产品名称的部分。 这个代码应该是有效的:
运行代码的屏幕截图:
# 2 楼答案
nextInt()
方法在按enter键时不读取新行,因此nextLine()
方法只读取这一新行有两种变通方法:
你可以这样把
nextLine()
放在nextInt()
后面:或者,更好的是,您可以使用
nextLine()
读取所有输入,并将字符串解析为您需要的任何内容: