为什么我必须编写两次才能在数组列表中添加输入?
原学程将引见为何我必需编辑二次能力在数组列表中添减输出?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。
成绩描写
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
System.out.println("You wrote the following products
");
for (String naam : arrayList) {
System.out.println(naam);
}
}
我正在测验考试从用户那边夺取1些输出并将它们保存到arraylist中。成绩是我必需写二次项能力将项添减到列表中。我想没有出为何!
推举谜底
每一次写进readLine()
时,都邑读与1言。在此轮回中,
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
涌现二次readLine()
,是以每一次迭代皆读与二言。第1言一直添减到列表中,而且没有与q
查对;第两言永久没有会添减到列表中,而且一直与q
查对。
您应当只履行1次nextLine
:
while (true) {
System.out.println("Enter a product");
String product = input.nextLine(); // only this one time!
if (!product.equalsIgnoreCase("q")) {
arrayList.add(product);
} else {
break;
}
}
佳了闭于为何我必需编辑二次能力在数组列表中添减输出?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。