我想读取用户输入,如下所示: 11 12 13 14 15 16
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
System.out.println(sc.next());
}
System.out.println("Test");
但它更新的是走出while循环并输出"Test“。我怎么能读到这些输入呢?
发布于 2014-12-21 21:59:53
你可以根据你是想退出还是不想退出来打破循环。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String next = sc.next();
if (next.equals("q")) { //if user press q then break the loop
break;
}
System.out.println(next);
}
System.out.println("Test");
}
发布于 2014-12-21 22:00:53
使用如下api:
while(sc.hasNextInt()){
int aba= sc.nextInt();
if (aba == 0) {//or even non numeric value here would let this loop exit
break;
}
}
因此您需要输入0,或者甚至以其他方式输入非数字值才能跳出循环。nextLine方法只会读取整行一次,然后您需要解析它,然后将其转换为整数,所以使用sc.nextInt会很好,它将为您做这项工作。
https://stackoverflow.com/questions/27589960
复制相似问题