我试图通过一行输入检索用户输入:例如5,6,4,8,9使用扫描仪分隔符为逗号。如何检索任意数量的整数这种类型的输入?也就是说,不需要询问用户他们希望输入多少个整数。这里是我一直在使用的代码,但是当我希望它打破时不能有while循环中断。请注意,我保留System.out来跟踪程序当前正在运行的位置。一个令人困惑的部分是,我可以用这种格式获取用户输入,但是程序停止并再次请求用户输入,那么如果输入是一个整数,它会要求更多输入,直到用户输入更长的输入流(至少输入2,6 +)然后输出字符串“调用break”,然后“while while while循环”。使用扫描仪处理用户输入
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Lab1 {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
@SuppressWarnings("resource")
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberList;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(",");
System.out.print("Enter integers: ");
while(scanner.hasNext())//------------------------while loop------
{
if(scanner.hasNextInt())
{
numberList = scanner.nextInt();
numbers.add(numberList);
System.out.println(numbers.toString() + " " + numbers.size());
}
else
{
System.out.println("called break");
break;
}
System.out.println("Inside of while loop");
}//-------------------------------------------------end of while loop------
System.out.println("outside of the while loop now");
}
}
Input: 1,2,3,4,5
Enter integers: 1,2,3,4,5
[1] 1
Inside of while loop
[1, 2] 2
Inside of while loop
[1, 2, 3] 3
Inside of while loop
[1, 2, 3, 4] 4
Inside of while loop
我仍然即使是5后不整和计划正在等待更多的投入,现在如果我在末尾插入一个非整数值,我得到同样的事情while循环中。在这两个结果之后,一旦用户输入更多值(1,2),程序退出while循环并成功完成。一旦我完成使用逗号分隔符方法输入整数,我该如何使while循环中断?
示例代码+1:P – TheLostMind
这似乎工作真的很棒。我得到了零件的长度,并发现它是正确的尺寸。这是否意味着所有的“,”字符都从数组列表中删除? – user100165
是的,这是通过'split(“,”)'方法完成的。 – Christian