我无法弄清楚为什么以下程序不起作用。请帮帮我,我在哪里弄错了。谢谢。
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
int[] numbers = new int[100];
int largestNumber = 0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
Scanner sc = new Scanner(System.in);
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
}
}
答案 0 :(得分:0)
我认为Scanner
非常复杂,并且在很多时候都不起作用。以下是老式的方法:
public class LargestNumber {
public static void main(String[] args) {
int largestNumber=0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while (!(line = r.readLine()).equals("finish")) {
int val = Integer.parseInt(line);
if (val > largestNumber)
largestNumber = val;
}
System.out.println("The largest number is: " + largestNumber);
}
}
为此,请在新行中输入每个数字。我在这里使用了一个较短的算法,即读取一个数字,如果它大于目前为止的最大数,那么新数字是迄今为止的最大值
答案 1 :(得分:0)
这部分:
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
毫无意义。你:
你应该做的事情更简单:
检查下一个标记:
重复此操作最多100次;
答案 2 :(得分:-1)
根据文件:
抛出: InputMismatchException - 如果下一个标记与整数正则表达式不匹配,或超出范围
所以我可以做到这一点:
int counter = 0;
while (counter < numbers.length) {
if (sc.hasNextInt()) {
numbers[counter++] = sc.nextInt();
} else {
if (sc.hasNext("finish")) {
sc.close();
break;
} else {
System.out.println("It's neither number nor 'finish'.");
sc.next();
}
}
}
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
希望有所帮助