Home > Software design >  initializing a static array with a variable within the main method
initializing a static array with a variable within the main method

Time:03-23

I am currently learning java, and I have an assignment that is requiring that we make methods and to distribute program functionality.

I am asking the user to enter how many scores each student will have and storing it to a variable within the main method. I want to use that stored information to define the length of my static array so I can use the array in other methods. Am I making any sense lol.. Hopefully some of my code will help.

static Scanner inputDevice = new Scanner(System.in);
static String[] studentName = new String[3];
static Double[] studentScores = new Double[numOfScores];


public static void main(String[] args) {
    // TODO Auto-generated method stub
    
    System.out.print("How many scores per student? \n");
    int numOfScores = Integer.parseInt(inputDevice.nextLine());
    
    
    
    for (int i = 0; i < 3 ;  i  )
    {
        System.out.printf("\nEnter Name for student %d: ", i 1);
        studentName[i] = inputDevice.nextLine();
        
        System.out.printf("\nEnter Scores for %s \n", studentName[i]);
        
        
        for (int j = 0; j < studentScores.length ; j  )
        {
            System.out.printf("Quiz %d:", j 1);
            studentScores[j] = Double.parseDouble(inputDevice.nextLine());
            
        }
        
    }
    
    System.out.print("\n\t\t\t\tMenu\n\n");
    System.out.print("1. Class Average \n2. Student Average \n3. Quiz Average");
    
    System.out.print("\n\nEnter Choice number, or x to exit:");
    
    

}

public static int classAverage()
{
    for (int k = 0; k < studentScores.length; k  )
    {
        
    }
}

CodePudding user response:

so I can use the array in other methods

Your array is declared STATIC, so it is already accessible to any other methods that are also STATIC, like your classAverage() method.

That is not the main problem, though. You need to delay instantiating the array until after you know how big to make it.

Change:

static Double[] studentScores = new Double[numOfScores];

To:

static Double[] studentScores; 

Then create the array once you know how big to make it:

int numOfScores = Integer.parseInt(inputDevice.nextLine());
studentScores = new Double[numOfScores];

But...how do you plan on using this SINGLE 1D array to hold the scores for MULTIPLE students? As currently written, the scores array will only ever hold the scores for the last student as you are overwriting the existing values with the new values for the current student.

CodePudding user response:

static double [] arr;

public void static main(){

    //GET nofscore
    arr = new double[nofscores]
}
  •  Tags:  
  • java
  • Related