HasNextInt()无限循环 [英] HasNextInt() Infinite loop

查看:154
本文介绍了HasNextInt()无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//input: multiple integers with spaces inbetween
    Scanner sc = new Scanner(System.in);
    while(sc.hasNextInt())
    {
      //add number to list
    }

sc.hasNextInt()正在等待integer.仅当您输入non-integer字符时,该字符才会出现.

sc.hasNextInt() is waiting for an integer. It only breaks out if you input a non-integer character.

不久前我在这里看到了一个解决方案,但是我找不到了.

I saw a solution here before not too long ago but i cant find it anymore.

解决方案(如果您问我最好)是使用两台扫描仪.我似乎无法弄清楚它是如何使用两个扫描仪来解决此问题的.

The solution (was the best if you ask me) was using two scanners. I cant seem to figure out how it used two scanners to go around this problem.

sc.NextLine()可能是

用户可以输入多个整数,其数量未知.例如:3 4 5 1.在它们之间有一个空格.我要做的就是在使用两个扫描仪的同时读取整数并将其放在列表中.

A user can input multiple integers the amount is unknown. Ex: 3 4 5 1. There is a space inbetween them. All i want to do is read the integers and put it in a list while using two scanners.

推荐答案

根据您的评论

用户可以输入多个整数,其数量未知.例如:3 4 5 1.在它们之间有一个空格.我要做的就是在使用两个扫描仪的同时读取整数并将其放在列表中.

A user can input multiple integers the amount is unknown. Ex: 3 4 5 1. There is a space inbetween them. All i want to do is read the integers and put it in a list while using two scanners.

您可能正在寻找:

  • 扫描程序,它将从用户读取行(并且可以在需要时等待下一行)
  • 另一台扫描仪,它将处理从行中分离出来的每个数字.
  • scanner which will read line from user (and can wait for next line if needed)
  • another scanner which will handle splitting each number from line.

因此您的代码可能类似于:

So your code can look something like:

List<Integer> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("give me some numbers: ");
String numbersInLine = sc.nextLine();//I assume that line is in form: 1 23 45 

Scanner scLine = new Scanner(numbersInLine);//separate scanner for handling line
while(scLine.hasNextInt()){
    list.add(scLine.nextInt());
}
System.out.println(list);

这篇关于HasNextInt()无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆