为什么在循环时在Java中额外输入?
该计数是扫描6个输入,然后给出(前5个术语的总和)/ 5的结果。第6个输入只是额外的,代码的更改可以避免。我最多只能接受5个输入。 [计数的设置值< 4没有帮助]。
import java.util.Scanner;
public class a_03 {
///Average of five numbers
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int sum = 0, count = 0;
System.out.println("Enter five integers: ");
while (sc.hasNextInt() && count < 5) {
int num = sc.nextInt();
sum += num;
count++;
}
double mean = sum / count;
System.out.println(mean);
}
}
that count is scanning 6 inputs and then giving the results of (sum of first 5 terms )/ 5. the 6th input is just extra , changes in the code so it can be avoided . I want it to only take 5 inputs at most. [setting value of count<4 isn't helpful].
import java.util.Scanner;
public class a_03 {
///Average of five numbers
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int sum = 0, count = 0;
System.out.println("Enter five integers: ");
while (sc.hasNextInt() && count < 5) {
int num = sc.nextInt();
sum += num;
count++;
}
double mean = sum / count;
System.out.println(mean);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
sc.hasnextint()
表示“如果用户键入的下一个单词是整数”。确定这一点的唯一方法是等待用户键入另一个单词。由于您将其称为六次(带有五个
sc.nextint()
),因此用户必须输入六个值,其中最后一个值留在缓冲区中,等待sc。 NextInt()
消耗它。该解决方案不是要检查用户是否不打算阅读另一个整数。您可以通过在
中翻转订单时做到这一点,而
循环:由于
a&amp;&amp; b
仅评估b
如果a
为true(称为“短路”),当count&lt&lt; 5
,而不是首先检查用户是否输入另一个整数。sc.hasNextInt()
means "if the next word the user typed is an integer". The only way to determine this is to wait for the user to type another word.Since you call it six times (along with five
sc.nextInt()
), the user will have to enter six values, where the last one is left in the buffer waiting for asc.nextInt()
to consume it.The solution is not to check whether the user entered another integer if you don't plan to read it. You can do this by flipping the order in your
while
loop:Since
a && b
only evaluatesb
ifa
is true (called "short circuiting"), it will stop whencount < 5
instead of first checking if the user entered another integer.我终于找到了正确的解决方案,为什么我没有,而是在调用扫描仪实例上的hasnextint()方法之前评估计数条件解决了问题
例如
I finally find the correct solution I don't why but evaluating the count condition before calling the hasNextInt() method on the Scanner instance solved the problem
FOR EXAMPLE