程序重复输出中的条目

时间:2017-03-16 18:30:27

标签: java

程序代码正常工作,但输出重复了一些 投入。我似乎无法弄清楚为什么它会重复第一个条目以及最后一个条目。

import java.util.Scanner;

public class ArraySum {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        final int NUM_ELEMENTS = 8;             // Number of elements
        int[] userVals = new int[NUM_ELEMENTS]; // User input
        int i = 0;                              // Loop index
        int greaterVal = 0;                     // Find greater #'s than 21

        // Prompt user to populate array 
        System.out.println("Enter " + NUM_ELEMENTS + " integer values...");
        for (i = 0; i < NUM_ELEMENTS; ++i) {
           System.out.println("Value: ");
           userVals[i] = scnr.nextInt();
        }

        // Determine #'s greater than 21
        int greaterVal = userVals[0];
        System.out.print("#'s greater than 21 are: ");
        for (i = 0; i < NUM_ELEMENTS; ++i) {
            if (userVals[i] >= 21) {
                greaterVal = userVals[i];
            }
            // Code is supposed to only display #'s greater than 21 once
            System.out.print(" " + greaterVal + " ");
        }
        return;
    }
}

2 个答案:

答案 0 :(得分:0)

  for (i = 0; i < NUM_ELEMENTS; ++i) {
       if (userVals[i] >= 21) {
       greaterVal = userVals[i];
    }
    // Code is supposed to only display #'s greater than 21 once

    System.out.print(" " + greaterVal + " ");
    }

格式化非常糟糕,这个片段不正确。您应该立即打印值,而不是保存以供日后使用。

答案 1 :(得分:0)

这是因为你在条件System.out.print(" " + greaterVal + " ");之外提到if (userVals[i] >= 21),这就是为什么如果循环中的当前值小于21并且如果之前的值大于21则由GreaterVal变量保持的值然后它会再次打印上一个值。 更新你的代码

for (i = 0; i < NUM_ELEMENTS; ++i) {
            if (userVals[i] >= 21) {
                greaterVal = userVals[i];
            // Code is supposed to only display #'s greater than 21 once
            System.out.print(" " + greaterVal + " ");
            }    
        }

此外,如果您只需要打印21个以上的值,那么您不需要更大的变量,只需要这个

 for (i = 0; i < NUM_ELEMENTS; ++i) {
                if (userVals[i] >= 21) {
                // Code is supposed to only display #'s greater than 21 once
                System.out.print( " "+ userVals[i] + " ");
                }    
            }