mar
mar

Reputation: 53

Storing multiple user input in arrays

This program will ask the user for students name and grade then displays both. The values that the user inputs are stored in array names & array grade. I use a counter controlled for loop to gather user input into the arrays. What if I wanted to enter multiple grades for each student?? Fairly new to programming, any input or thoughts would be greatly appreciated on how to do so...

public class Five {

public static void main(String[] args) {
    int students;

    Scanner input = new Scanner(System.in); //created input scanner


System.out.println("How many students are on your roster? If you wish to exit please type 00: ");// Initializing statement for program************
students = input.nextInt();

       if(students == 00) { //Exit program****************
       System.out.println("Maybe Next Time!!");
           System.exit(0);
         }

String[] names = new String[students];// Array names*******
String[]grade = new String[students]; //Array grade********

// Use Counter to go through Array**************************
        for(int counter =0; counter < students; counter++){
        System.out.println("Enter the name of a student: " +  (counter +1));
        names [counter] = input.next();
        System.out.println("Now enter that students grade A, B, C, D OR F: ");
        grade [counter] = input.next();
        }

input.close();// End Scanner object
//Use For loop for Printing names and grades entered by the user**************
System.out.println("Your students names and grades are as follows: ");
        for(int counter =0; counter < students; counter++){
        System.out.println("Name: " + names[counter]);
        System.out.println("Grade: " + grade[counter]);
        }
    }
}

Upvotes: 3

Views: 8550

Answers (2)

Jennifer
Jennifer

Reputation: 210

You could use a ragged array for the grades to enter more than one You would need to declare it so here is a way to do that.

    String[] names = new String[students];// Array names*******
    String[][]grade = new String[names][]; //Array grade********

      for(int i=0; i<names[i];i++)
  {System.out.println("How many grades will you enter for "+names[i]+"?")
   int temp=input.nextInt();
  for(int j=0; j<names[i][temp-1];j++){
  grad[i][j]=input.next();         
           }}

Upvotes: 3

anaxin
anaxin

Reputation: 710

You should probably make a Student class and a Grades class and store them as objects. Using a data structure your best choice is a .

HashMap<String, List<String>> grades = new HashMap<>();
grades.put("Jack", new ArrayList<>());
grades.get("Jack").add("A");

You can find out more about HashMap here

Upvotes: 2

Related Questions