当我尝试执行大量输入时,我遇到了问题。该程序的目标是打印出数组中的最小数字和最高数字。我的目标是输入300个号码,但我的终端拒绝接受这么高的金额。但是,当我输入100个数字时,它完全正常。有人在尝试使用大量输入时可以解释这个程序有什么问题,以及为了让程序运行我可以做些什么的任何建议吗?
import java.util.Scanner;
class maxMinArray {
public static void main(String[] args) {
int input = 3;
int[] highLow = new int[input];
int highest = 0;
int lowest = 100000;
Scanner scan = new Scanner(System.in);
System.out.println("input data:");
for (int i = 0; i < input; i++) {
highLow[i] = scan.nextInt();
if (highLow[i] > highest) highest = highLow[i];
if (highLow[i] < lowest) lowest = highLow[i];
}
System.out.println("answer:");
System.out.println(highest + " " + lowest);
}
}
答案 0 :(得分:2)
首先在scan.nextLine()
之后添加low[i] = high[i] = scan.nextInt();
。 Scanner
之后的scan.nextInt()
缓冲区中仍有回车符/新换行符,这会在下次尝试读取错误时导致错误...
所以当我要求输入数据并且粘贴后立即复制粘贴300个整数
这会改变一些事情,尝试更像......
String text = scan.nextLine();
Scanner parse = new Scanner(text);
int i = 0;
while (parse.hasNextInt()) {
highLow[i] = parse.nextInt();
if (highLow[i] > highest) {
highest = highLow[i];
}
if (highLow[i] < lowest) {
lowest = highLow[i];
}
i++;
}
<强>更新强>
更好的解决方案可能是将所有数字放入文本文件并读取文本文件......
try {
Scanner parse = new Scanner(new File("Test.txt"));
int i = 0;
while (parse.hasNextInt()) {
highLow[i] = parse.nextInt();
if (highLow[i] > highest) {
highest = highLow[i];
}
if (highLow[i] < lowest) {
lowest = highLow[i];
}
i++;
}
System.out.println("answer:");
System.out.println(highest + " " + lowest);
} catch (FileNotFoundException exp) {
exp.printStackTrace();
}
您可以使用Scanner
提示用户输入文本文件的名称,而不是硬编码
答案 1 :(得分:0)
试试这个。我尝试过将400个数字整数从0复制到10000,但我没有收到错误。如果不起作用,则控制台的输入缓冲区不允许大量数据。
int[] list = new int[400];
int highest = 0;
int lowest = 100000;
int num;
int n=0;
String inputConsole;
Scanner scan = new Scanner(System.in);
System.out.println("input data:");
inputConsole=scan.nextLine();
Scanner input = new Scanner(inputConsole);
while (input.hasNext()) {
if (input.hasNextInt()) {
num=list[n++]= input.nextInt();
if (num > highest) highest = num;
if (num < lowest) lowest = num;
} else {
input.next();
}
}
System.out.println("answer:");
System.out.println(highest + " " + lowest);