cube dash cube dash - 1 month ago 6
Java Question

Any idea about array; I am doing array list project

I wanted the output to be like this using array list but my code is not giving me the right output.

output

My code is:

package studentraanking;

import java.util.*;

public class Studentraanking {

public static void main(String[] args) {


System.out.println("Enter # of Students:");
Scanner input = new Scanner(System.in);
int arraySize = input.nextInt();
System.out.println("Enter # of Subjects");
Scanner sub = new Scanner(System.in);
int arrays = sub.nextInt();
ArrayList<String> array = new ArrayList<String>();

ArrayList<String> arraysss = new ArrayList<String>();

System.out.println("Enter "+arrays+" Subjects");
for (int i = 0; i < arrays; i++) {

String sj = input.next();
array.add(sj);



for (int x = 0; x < arraySize; x++) {

System.out.print((x+1)+". Name:");
String arval = input.next();
System.out.println("Grade in : " + sj );
int grade = input.nextInt();
arraysss.add(arval);
}





}
}

}


wrong output of my code

I wanted to finish entering all the subjects before asking the name of the student then ask his grade for every subjects that i entered please help thanks

Answer

Your problem is that you nested your for loops. Do this:

//Input all your subjects
for (int i = 0; i < arrays; i++) {
    //input all your subjects
    String sj = input.next();
    array.add(sj);


}//this is the closing brace for the first for loop, which you had surrounding the loop below


 //input your grades
for (int x = 0; x < arraySize; x++) {

     System.out.print((x+1)+". Name:");
     String arval = input.next();
     System.out.println("Grade in : " + array.get(x) );
     int grade = input.nextInt();
     arraysss.add(arval);
}