我正在尝试自学Java编程,偶然发现了斯坦福大学提供的CS106A类(class)。这是一个很棒的免费在线类(class)。我看了几个lecture videos到目前为止我很喜欢它们。我现在正在尝试做作业,但我遇到了这个问题,我自己无法解决。
这是this assignment中的数字5 。基本上,它要求学习者创建一个控制台程序来获取用户输入的一些整数并作为响应,显示最大和最小的数字。
以下代码是我所做的,问题是当我尝试输入整数时,它将跳过偶数个输入。例如,如果我在控制台输入 3,12,6,15,9,它只会得到 3,6,9 ,忽略 12,15。
我做错了什么?任何帮助将不胜感激。
import java.util.*;
public class Ass2_5MaxMinNumbers {
public static void main (String args[]) {
Scanner scanner;
System.out.println ("This programme finds the largest and smallest numbers.");
System.out.println ("After finished entering, enter \"End\" (without double quotes) to show the results.");
List<Integer> list = new ArrayList<Integer>();
int max = 0, min = 0;
do {
scanner = new Scanner(System.in);
if(scanner.hasNextInt()){
int x = scanner.nextInt();
list.add(x);
System.out.println("user input: " + x);
} else if(!scanner.hasNext("End")){
System.out.println("Please enter an integer!");
}
} while (!scanner.hasNext("End"));
max = list.get(0);
min = list.get(0);
for(int x = 1; x < list.size(); x++){
if(list.get(x) > max){
max = list.get(x);
} else if(list.get(x) < min){
min = list.get(x);
}
}
System.out.println ("Smallest number: " + min);
System.out.println ("Biggest number: " + max);
}
}
最佳答案
Scanner.nextInt
方法仅从用户传递的输入中读取下一个标记。因此,它会忽略每个输入末尾的换行符。该换行符将作为下一次调用 Scanner.nextInt
的输入,因此您的输入将被忽略。
每次调用 Scanner.nextInt
后,您可以使用空白的 Scanner.nextLine
来使用换行符。
if(scanner.hasNextInt()){
int x = scanner.nextInt();
scanner.nextLine(); // Add a blank nextLine
list.add(x);
System.out.println("user input: " + x);
}
或者您也可以仅使用 scanner.nextLine()
读取整数
,并使用 Integer 将输入转换为
。 整数
.parseInt
if(scanner.hasNextInt()) {
int x = 0;
try {
x = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
list.add(x);
System.out.println("user input: " + x);
}
实际上,由于您在 if 中使用 scanner.hasNextInt
,因此您实际上并不需要在 Integer.parseInt
周围使用 try-catch
code>,这样你就可以删除它。
更新:-
我会将您的 do-while
替换为 while
,并从内部删除 if-else
检查。
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if (input.equals("End")) {
break;
} else {
try {
int num = Integer.parseInt(input);
list.add(num);
} catch (NumberFormatException e) {
System.out.println("Please Enter an Integer");
}
}
}
关于Java:使用 hasNextInt 和 do-while 循环,它会忽略偶数次的整数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13429655/