Home > Enterprise >  How to use data collection in nested loop
How to use data collection in nested loop

Time:12-04

I can collect all of the input data, but I just can't seem to do anything with it. I would like to print all of data or add or subtract the numbers, perform calculations. I am not sure how to work with nested data.

import java.util.Scanner;

public class Names {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("How many students do you want to enter?");
        String[] names = new String[2];
        for (int stnumber = 0; stnumber < 2; stnumber  ) {
            System.out.println("Enter the first student "   (stnumber   1));
            names[stnumber] = input.next();

            String[] quiz = new String[2];

            for (int qznumber = 0; qznumber < 2; qznumber  ) {
                System.out.println("Enter quiz mark "   (qznumber   1));
                quiz[qznumber] = input.next();
            }
            String[] midterm = new String[1];
            for (int mtnumber = 0; mtnumber < 1; mtnumber  ) {
                System.out.println("Enter midterm mark "   (mtnumber   1));
                midterm[mtnumber] = input.next();
            }

            String[] myfinal = new String[1];
            for (int fnnumber = 0; fnnumber < 1; fnnumber  ) {
                System.out.println("Enter final mark "   (fnnumber   1));
                myfinal[fnnumber] = input.next();
            }

        }
        input.close();

        System.out.println("The students marks are");
        for (int stnumber = 0; stnumber < 2; stnumber  ) {
            System.out.println(names[stnumber]);
        }
    }
}

CodePudding user response:

You should define a class to represent a Student:

public class Student {
    String name;
    String[] quizzes;
    String[] midterms;
    String[] finals;
}

Then, you will need a constructor to declare a new instance of a Student, here is an exmaple:

public Student(String name) {
    this.name = name;
    this.quizzes = new String[2];
    this.midterms = new String[2];
    this.finals = new String[1];
} 

Now you can create a new student in your main method like this:

Student newStudent = new Student("put the name here");

And store the quizzes, midterms, etc in that instance of the Student:

newStudent.midterms[0] = "midterm 1 grade";

CodePudding user response:

public class Student {
String name;
String[] quizzes;
String[] midterms;
String[] finals;
}


public Student(String name) {
this.name = name;
this.quizzes = new String[2];
this.midterms = new String[2];
this.finals = new String[1];
  • Related