ArrayList的扫描仪
问题描述:
在这个程序中,我的意思是说:它应该只能从用户那里通过扫描仪获得正数,如果它们是正数 - 它需要将它们添加到“列表”数组列表中。 由于某些原因,它不会在用户添加第一个数字时添加第一个数字,而只会添加第二个数字(并且它在每个while循环中都像这样运行)。ArrayList的扫描仪
有人可以帮忙吗? 谢谢! :-)
import java.util.ArrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class Second_EX_Advanced_2 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Please enter a positive number ... ");
Scanner INPUT = new Scanner(System.in);
while (INPUT.nextInt() > 0) {
list.add(INPUT.nextInt());
System.out.println(list);
}
INPUT.close();
}
}
*
答
你实际上走的是输入两次
while (INPUT.nextInt() > 0) { //first time here
list.add(INPUT.nextInt()); //second time here
System.out.println(list);
}
变化
int n;
while ((n=INPUT.nextInt()) > 0) { //first time here
list.add(n); //second time here
System.out.println(list);
}
现在应该很好地工作;
答
错误是在,而你的循环:
while (INPUT.nextInt() > 0) {
list.add(INPUT.nextInt());
System.out.println(list);
}
要扫描的第一个整数并加入第二个,如上所述。
在这里,你去与工作代码:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class Second_EX_Advanced_2 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Please enter a positive number ... ");
Scanner INPUT = new Scanner(System.in);
int num;
while ((num = INPUT.nextInt()) > 0) {
list.add(num);
System.out.println(list);
}
INPUT.close();
}
}
+0
谢谢所有:)它帮助分配 – Ofer
+0
您可以通过单击答案旁边的箭头接受此答案。这对社区有帮助。 :) –
你是消费在'while'条件的第一整数值。 – Mena
'while((value = INPUT.nextInt())> 0)'其中'value'的类型是int,然后是'list.add(value);' – XtremeBaumer
使用nextLine()将清除缓冲区,您在错误之后读取的下一个输入将是您输入的坏行之后的新输入。 – VedX