【问题标题】:Java While loop skipping lines, doing them every 2 cycles insteadJava While循环跳过行,而是每2个循环执行一次
【发布时间】:2013-02-12 00:31:54
【问题描述】:

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


}

}

【问题讨论】:

  • 如果您遵循 Java 命名约定,您的代码将更具可读性。例如。变量以小写字母开头。

标签: java loops


【解决方案1】:
    CurrentInput = In.nextInt();
    Scores[Counter] = CurrentInput;
    Total += In.nextInt();

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

【讨论】:

    【解决方案2】:
    CurrentInput = In.nextInt();
    Scores[Counter] = CurrentInput;
    Total += CurrentInput;
    

    改用这个。

    【讨论】:

      最近更新 更多