public void getDisMarks()
{
marks=new int[3];
System.out.print("Enter marks of Physics: ");
marks[0]=sc.nextInt();
System.out.print("Enter marks of Chemistry: ");
marks[1]=sc.nextInt();
System.out.print("Enter marks of Maths: ");
marks[2]=sc.nextInt();
}
So in this piece of code we are using array for 3 definite subjects. And we’re using scanner class to input from the user. Let’s say in the future I want to add a couple of more subject. So coding it again would not make it any flexible.
So I read that we could use arrayList, How can I use scanner class with arrayList similar to this piece of code.
>Solution :
You could do something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("How many marks to enter?");
int marksToEnter = sc.nextInt();
for (int i = 0; i < marksToEnter; i++) {
System.out.println("Enter next mark");
list.add(sc.nextInt());
}
System.out.println(list);
}