【发布时间】:2014-11-27 09:16:21
【问题描述】:
我的要求是:
输入的第一行包含一个整数 n(其中 n>=3)表示数组的大小。在下一行中,将有 n 个整数,由空格分隔,对应于数组中的 n 个元素。为此,我使用了以下代码:
Scanner length = new Scanner(System.in);
System.out.println("Please Enter Length of Aarry:");
int n=length.nextInt();
int[] numbers = new int[n];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements seperated by spaces: ");
String input = sc.nextLine();
StringTokenizer strToken = new StringTokenizer(input);
int count = strToken.countTokens();
//Reads in the numbers to the array
System.out.println("Count: " + n);
int[] arr = new int[n];
for(int x = 0;x < n;x++){
arr[x] = Integer.parseInt((String)strToken.nextElement());
System.out.println("values are: " + arr[x]);
}
但问题是:上面的代码将正确读取所有用空格输入的整数,但我也想指定输入值的限制。请帮助我如何实现这一点。
【问题讨论】:
-
不清楚你想要什么。如果用户输入的数字(令牌)过多,您想向用户显示错误信息吗?
-
@StijnGeukens 我认为 OP 想在阅读
n数字后停止阅读输入。 -
@johny 我认为他现在已经这样做了,但是如果 n > count 会失败
-
@StijnGeukens 我们现在可以输入比
n更多的数字,但数组arr中只有n 个值。但我认为 OP 想阻止我们输入比n更多的号码。 -
@johnny 如果用户输入的数字少于 n,它将抛出
NoSuchElementException
标签: java arrays string java.util.scanner