1

我正在编写一个作业程序,该程序应该读取未指定数量的 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();


}

}
4

2 回答 2

6
    CurrentInput = In.nextInt();
    Scores[Counter] = CurrentInput;
    Total += In.nextInt();

您正在调用两次In.nextInt(),即,您在每次循环迭代中读取两行。

于 2013-02-12T00:33:43.147 回答
1
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += CurrentInput;

改用这个。

于 2013-02-12T00:51:04.127 回答