所以我一直在学习Java,我偶然发现了一个问题,有人能告诉我它有什么问题吗?
package com.company;
import java.util.Scanner;
public class Main {
Scanner input = new Scanner(System.in);
int total = 0;
int grade;
int average = 0;
int counter = 0;
while (counter>10) {
grade = input.nextInt();
total += grade;
counter++;
}
average = total/10;
System.out.print("avg is: "+ aveg);
}
答案 0 :(得分:4)
while (counter>10) // while(0>10) ---> while(false){//Not executed}
虽然条件不为真,因为count为零所以当body不执行时
代替
while (counter<10)
并且还将你的代码放在函数中,因为在java中没有任何东西,除了在函数外部完成的声明和初始化
import java.util.Scanner;
public class Main {
//only declaration and initialization outside methods
public static void main(String a[]){
Scanner input = new Scanner(System.in);
int total = 0;
int grade;
int average = 0;
int counter = 0;
while (counter<10) {
grade = input.nextInt();
total += grade;
counter++;
}
average = total/10;
System.out.print("avg is: "+ average);
}
}
答案 1 :(得分:0)
同样在您的代码中,您甚至没有使用hasNextInt
方法检查是否存在下一个int值。
你的while循环不起作用,因为你在counter>10
开始时正在测试counter = 0
,所以它甚至不会进入while循环
除了你的while循环问题,你应该像这样修改代码
package com.company;
import java.util.Scanner;
public class Main {
Scanner input = new Scanner(System.in);
int total = 0;
int grade;
int average = 0;
int counter = 0;
while (counter>10) {
if(input.hasNextInt()){
//this line is important ,
//else code will throw an exception if no more input is found next
grade = input.nextInt();
total += grade;
counter++;
}
}
average = total/10;
System.out.print("avg is: "+ aveg);
}