简体   繁体   English

扫描仪问题

[英]Issue with the Scanner

I'm new to the world of Java programming trying to input values through the scanner class using the code below. 我是Java编程领域的新手,它尝试使用下面的代码通过扫描器类输入值。

The issue is the Scanner is not opening up the console for user input and its displaying the average value to be zero by default. 问题是扫描仪没有打开控制台供用户输入,并且其显示的平均值默认为零。 Debugging the console is throwing a file not found exceptions error. 调试控制台将引发文件未找到异常错误。 Please advise... 请指教...

import java.util.Scanner;

public class Avg {

  int no = 0;
  int sum = 0;

  void average(){
    System.out.println("pls enter 5 numbers");
    Scanner s = new Scanner(System.in);
    for(int i = 0; i > 5;  ) {
      no = s.nextInt();
      sum = no + sum;
      i++;
    }
    int avg = sum / 5;
    System.out.println(avg);
  }

  public static void main(String[] h){
    Avg s = new Avg();
    s.average();
  }
}

The first for loop should have i < 5 condition but it is i > 5 in your code. 第一个for循环的条件应为i < 5但在您的代码中为i > 5 So it makes 0 iterations. 因此,它进行了0次迭代。

For loop is having issue. For循环出现问题。 You set the value of i to 0 and check if it is greater than 5 . 您将i的值设置为0并检查它是否大于5 Not at all possible. 根本不可能。 it turns false . 它变成false Please change the conditional check to 请将条件检查更改为

for(int i=0;i<5;){
no=s.nextInt();
sum=no+sum;
i++;
}

Otherwise, i will be always lesser than 5 and will not get inside the loop. 否则, i将始终小于5并且不会进入循环。 So, the value of avg will be always 0 因此, avg的值将始终为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM