Keep Inputting values until array is full?

2.2k views Asked by At

I'm creating a class that keeps the scores of quizzes taken by students. Here's the specs: The constructor is to a. Create an instance of an int-type array with the length of input parameter. Each element in the array is initialized as -1. b. The count is set as 0. It is not the length of array but the number of valid scores. In other words, the scores is a partially filled array, and the count is used as an END position of valid scores. c. Set the name with the second input parameter.

I'm having trouble with the add method. I have to input the size for how many quizzes a student will take and then add the scores for each quiz they took until the array gets full.

Example: If I input the size of the quiz to be 3, I'll be able to add 3 different scores, but if i go over 3 it has to display a message like "Array is full. The value _____ cannot be added".

here's what I have so far for my class:

public class Quiz {

    private static int [] scores;
    private  int count;
    private static String name;


    public Quiz (int[] scores, int count, String name){
        int size=0;
        scores=new int [size];
        count=0;
        name=" ";
    }

    public void addScores( int [] scores){
        int size=0;
        scores=new int [size];
        for(int i=0; i<size;i++)
            if(i<size)
               System.out.println(scores[i]);   
            else
                System.out.println("Array is full! the value"+ " " + scores + " "+ "cannot be added.");

}

here's part of test driver code :

Scanner in = new Scanner (System.in);

do {
    System.out.println("\nPlease enter a command or type ?");
    String choice;

    choice = in.next().toLowerCase();
    command = choice.charAt(0);
    switch (command) {
        case 'n':
            System.out.println("[Create a new data]");
            System.out.println("[Input the size of quizzes]:"+ " ");
            int size=in.nextInt();
            String linebreak = in.nextLine();
            System.out.println("[Input the name of student]:"+ " ");
            String name=in.nextLine();

            break;

        case 'a':
            System.out.println("a [Add a score]:"+ " ");{

            int i=0;            
            i=in.nextInt();

            break;
    }
}
1

There are 1 answers

2
Daryl Bennett On

Look at the code in your addScores method. Your passing it an int array scores but your setting its value to a new array of size 0. You need to omit the following line:

 scores=new int [size];

And you need to set your size variable to size of the incoming array.

 int size = scores.length;