Home > Back-end >  How do I add the name of the subjects rather than the index value?
How do I add the name of the subjects rather than the index value?

Time:02-13

public void getMarks(int numberOfSubject, String nameOfSubject) throws IOException{
    marks = new int[numberOfSubject];
    nameOfSubject = Arrays.toString(new String[numberOfSubject]);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    for(int i = 0; i< numberOfSubject;i  ){
        System.out.println("Enter the name of the subject " i);
        numberOfSubject[i] = br.readLine();
        System.out.println("Enter "  i  " Subject Marks:");
        marks[i] = Integer.parseInt(br.readLine());
        System.out.println(" ");
    }
}

Hello Everyone!, hope you are doing fine.

  1. So I was writing a problem statement for entering the grade of the students.
  2. So I'm stuck at this part of the code, where when I print the Enter the subject marks it shows the index value
System.out.println("Enter "  i  " Subject Marks:");
  1. Instead of the index value I want to actually add the subject name.
  2. Can somebody please guide me? Thank you In advance.

CodePudding user response:

Considering you want to read details for given number of subjects, and store it, the ideal way is to use a Map. Please find solution below

public void getMarks(int numberOfSubjects) throws IOException{ //Removed 2nd parameter as it is not reqd.

    Map<String, Integer> subjectMarksMap = new HashMap<>();
   
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    for(int i = 0; i< numberOfSubjects;i  ){
        System.out.println("Enter the name of the subject " i);
        String subject = br.readLine()
        System.out.println("Enter "  subject  " Subject Marks:"); //You need to use the above read subject name here, not i.
        Integer marks = Integer.parseInt(br.readLine());
        subjectMarksMap.put(subject, marks);
        System.out.println(" ");
    }

}
  •  Tags:  
  • java
  • Related