简体   繁体   中英

Filling 1D Array without for loop in java

I have a task of filling an array using a sentinel controlled while loop (I have to use 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]);


}

This is my current code, the result from println is 15 if I input : 1, 2, 3, 4, 5, -1. Could you please help me finding what have I done? I am a new java user.

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

Your code can only handle a fixed number of scores, which is 5. It will give you nonsense for less than 5 scores and wrong answer for 6 to 10 scores, and ArrayIndexOutOfBoundsException for more than 10 scores. Because you are using a fixed-length array of 10 elements, and manually summing the first 5 elements. You are better off using a dynamic list for storing the user input and use a for-loop to handle the summation.

Apart from this major issue, the code that handles user input is repeated twice, and it doesn't handle non-integer strings. You should put that code in a method and give it a proper name.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM