我正在编写一个家庭作业程序,该程序应该读取未指定数量的0-100分(最多100分)并在-1之后停止或输入任何负数。 我把它放入Do While循环中,当通过Scanner拉入-1时,该循环被设置为终止。循环有一个计数器,用于跟踪循环经过的次数,加法器将所有输入行加在一起以便稍后计算平均值,以及在输入值检查到之后将输入值发送到数组的方法看看数字是否为-1。 而不是这样做,循环只是每2个循环递增计数器而-1只会在偶数循环数上终止循环,否则它将等到下一个循环终止。这完全让我困惑,我不知道为什么会这样做。有人可以指出错误吗?提前致谢!这就是我到目前为止所做的一切。
import java.util.Scanner;
public class main {
//Assignment 2, Problem 2
//Reads in an unspecified number of scores, stopping at -1. Calculates the average and
//prints out number of scores below the average.
public static void main(String[] args) {
//Declaration
int Counter = 0; //Counts how many scores are
int Total = 0; //Adds all the input together
int[] Scores = new int[100]; //Scores go here after being checked
int CurrentInput = 0; //Scanner goes here, checked for negative, then added to Scores
Scanner In = new Scanner(System.in);
do {
System.out.println("Please input test scores: ");
System.out.println("Counter = " + Counter);
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
Counter++;
} while ( CurrentInput > 0);
for(int i = 0; i < Counter; i++) {
System.out.println(Scores[i]);
}
System.out.println("Total = " + Total);
In.close();
}
}
答案 0 :(得分:6)
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
您正在调用两次In.nextInt()
,即您在每次循环迭代中读取两行。
答案 1 :(得分:1)
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += CurrentInput;
改为使用它。