[英]Java - losing first user input using a while loop
Good morning all, 大家早上好,
I am currently learning coding / Java. 我目前正在学习编码/ Java。 The task I need to do is;
我需要做的任务是: make a program that takes user input and returns the highest and lowest entry.
制作一个需要用户输入并返回最高和最低条目的程序。 I have to use a while loop to keep it simple.
我必须使用while循环使其保持简单。 At the moment I got this:
目前,我得到了:
System.out.println("Enter numbers, Q to finish: ");
int largest = sc.nextInt();
int smallest = sc.nextInt();
while (sc.hasNextInt()) {
int number = sc.nextInt();
if(number > largest) {
largest = number;
}
else if(number < smallest){
smallest = number;
}
}
System.out.printf("Largest: %d Smallest: %d", largest, smallest);
The problem is that it skips the first user entry. 问题在于它跳过了第一个用户输入。 After some testing I saw that when I only enter 1 number and press QI get a error.
经过一些测试,我发现当我仅输入1个数字并按QI时会出现错误。 If I enter;
如果我输入; 10 - 20 - 30, the return is;
10-20-30,回报为; Largest: 30 Smallest: 20.
最大:30最小:20
Anyone has a idea why it skips the first user entry? 有人知道为什么它跳过第一个用户输入吗?
Replace these 2 lines: 替换以下两行:
int largest = sc.nextInt();
int smallest = sc.nextInt();
with 与
int largest = sc.nextInt();
int smallest = largest;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.