Home > Software engineering >  How to generate multiple "Variables" in a list by Just entering the specific number of &qu
How to generate multiple "Variables" in a list by Just entering the specific number of &qu

Time:04-19

this is my first post here and I'm an aspiring programmer as well, so please when you see that I'm kind of talking nonsense don't go too harsh on me.

I'm having a bit of a problem creating a programme that I had in mind, this programme needs to ask the user for input on how many students are going to be marking, the user will insert a certain amount (example 10) after that is going to ask us to put for each of the 10 students a score in percentages.

what I had in mind was to create a For Loop to generate multiple “Variables” but I'm kind of lost on how I'm going to interact with each and one of them, so if you please could help me try to solve this problem that would be great, and please if there is a better way to do it please try to explain it to me as if you are trying to explain to a child. XD

CodePudding user response:

The most simple way is just to use for loop for writting and for reading. I don't know why you need this but i hope it helps.

Scanner sc= new Scanner(System.in);
       System.out.println("Insert number of students: ");
                String student = sc.nextLine();
                int studenti = Integer.parseInt(student);
                 int[] array = new int[studenti];
                for (int i = 0; i<studenti;i  )
                {
                    System.out.println("Insert a score in procentage: ");
                    String score = sc.nextLine();
                    
                    array[i]= Integer.parseInt(score);
                }
                System.out.println("\n Procentages are: ");  
                for (int i=0; i<studenti;i  )
                {
                    System.out.println(array[i]);
                }

Best regards!

Blaz

CodePudding user response:

So you definitely need an Array for this. There are several types you could use. For you use-case the standard Array will do.

If you want to comply to object-oriented style, you should use a Student class. But I will do it with strings for now:

int numberOfStudents = 10;
String[] students = new String[numberOfStudents];

// now you can do:
students[0] = "John";
students[1] = "Michael";
// ...


// print all students
for(String student : students){
   System.out.println(student);
}

Another way of doing this is with Lists. They are a bit more performance costly than arrays but are way more convienient to work with as you don't have to know how much entries it will have. Look at this:

import java.util.ArrayList;
ArrayList<String> students = new ArrayList<Students>();

students.add("John");
students.add("Michael");
// ...


// print all students
for(String student : students){
   System.out.println(student);
}
  • Related