在java中填充没有for循环的1D数组

时间:2016-10-11 10:49:04

标签: java arrays loops for-loop

我有一个使用sentinel控制的while循环填充数组的任务(我必须使用JOptionPane)。

    int score[] = new int [10];
int x = 0;
int size = 0;
x = Integer.parseInt(JOptionPane.showInputDialog("Please enter the score"));

while ( x != -1){
score[size]= x ;
x = Integer.parseInt(JOptionPane.showInputDialog("Please enter the score"));
size++;    

}
System.out.println(score[0]+score[1]+score[2]+score[3]+score[4]);


}

这是我当前的代码,如果输入的话,println的结果为15:1,2,3,4,5,-1。 你能帮我找一下我做了什么吗?我是一个新的java用户。

2 个答案:

答案 0 :(得分:0)

int sent=0;
while(sent!=1){
    //append to array
    //do something which may change the value of sent
}

答案 1 :(得分:0)

你的代码只能处理固定数量的分数,即5分。对于6到10分,你会得到低于5分的废话和6到10分的错误答案,而对于超过10分,你会得到ArrayIndexOutOfBoundsException。因为您使用的是10个元素的固定长度数组,并且手动求和前5个元素。最好使用动态列表来存储用户输入,并使用for循环来处理求和。

除了这个主要问题,处理用户输入的代码重复两次,并且它不处理非整数字符串。您应该将该代码放在方法中并为其命名。

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class Filling1DArray {

    /**
     * Ask the user to enter an integer
     * @return The integer the user entered or -1 if the input is not an integer
     */
    private static int nextScore() {
        try {
            return Integer.parseInt(JOptionPane.showInputDialog("Please enter the score (or -1 to stop)"));
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public static void main(String [] args) {

        // Dynamic list to hold the user input
        List<Integer> scores = new ArrayList<>();

        // Get user input until she enters -1 or some non-integer
        int score;
        while ((score = nextScore()) != -1)
            scores.add(score);

        // Compute the sum using stream API
        System.out.println(scores.stream().reduce((a, b)->a+b).orElse(-1));

        // Or a simple ranged-for
        int sum = 0;
        for (int s : scores) sum += s;
        System.out.println(sum);
    }
}
相关问题