Home > Blockchain >  How to connect two class modules together in Java?
How to connect two class modules together in Java?

Time:02-26

I have a program that contains five .txt files. These files are read in and put into different arrays. One is an array of names. The other four are arrays with test scores.

Currently, the program does create the arrays correctly. Next the program is to calculate and display the average for each test (this works fine). Then the program prompts the user for a name. If a name is found a new menu will prompt the user to select which test they want the data on. (This works fine).

The problem: I have the main program class and another GradeBook class (does calculations) on another page. How do I connect the two pages together?

For example: If the studentName is 'Andrew' and it is found in studentNameArray, and I select 1 for which test score I want to see (scoreOneArray), say the number 88. My program finds 'Andrew' and '88'. What it does not do is send 'Andrew' and '88' to GradeBook to have the data compute test percentage (88/100) and find the corresponding letter grade (in this case 'B'). Lastly, then print students name, test score (88%), and the letter grade.

Program (main):

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        double test1Calculation;
        double test2Calculation;
        double test3Calculation;
        double test4Calculation;
        int i, j, k, l;
        int testOneSum = 0;
        int testTwoSum = 0;
        int testThreeSum = 0;
        int testFourSum = 0;
        int checker = 0;
        int index=0;
        String choice;

        Scanner students = new Scanner(new File("names.txt"));
        Scanner TestOne = new Scanner(new File("testOne.txt"));
        Scanner TestTwo = new Scanner(new File("testTwo.txt"));
        Scanner TestThree = new Scanner(new File("testThree.txt"));
        Scanner TestFour = new Scanner(new File("testFour.txt"));

        String token1 = "";
        List<String> studentName = new ArrayList<>();
        while (students.hasNext()) {
            // find next line
            token1 = students.next();
            studentName.add(token1);
        }

        String[] studentNameArray = studentName.toArray(new String[0]);

        List<Integer> scoreOne = new ArrayList<>();

        // while loop
        while (TestOne.hasNext()) {
            // find next line
            Integer token2 = TestOne.nextInt();
            scoreOne.add(token2);
        }

        Integer[] scoreOneArray = scoreOne.toArray(new Integer[0]);

        List<Integer> scoreTwo = new ArrayList<>();

        // while loop
        while (TestTwo.hasNext()) {
            // find next line
            Integer token3 = TestTwo.nextInt();
            scoreTwo.add(token3);
        }

        Integer[] scoreTwoArray = scoreTwo.toArray(new Integer[0]);

        List<Integer> scoreThree = new ArrayList<>();

        // while loop
        while (TestThree.hasNext()) {
            // find next line
            Integer token4 = TestThree.nextInt();
            scoreThree.add(token4);
        }

        Integer[] scoreThreeArray = scoreThree.toArray(new Integer[0]);

        List<Integer> scoreFour = new ArrayList<>();

        // while loop
        while (TestFour.hasNext()) {
            // find next line
            Integer token5 = TestFour.nextInt();
            scoreFour.add(token5);
        }

        Integer[] scoreFourArray = scoreFour.toArray(new Integer[0]);

        for (i = 0; i < scoreOneArray.length; i  )
            testOneSum  = scoreOneArray[i];
        test1Calculation = (double) testOneSum / 5;

        for (j = 0; j < scoreTwoArray.length; j  )
            testTwoSum  = scoreTwoArray[j];
        test2Calculation = (double) testTwoSum / 5;

        for (k = 0; k < scoreThreeArray.length; k  )
            testThreeSum  = scoreThreeArray[k];
        test3Calculation = (double) testThreeSum / 5;

        for (l = 0; l < scoreFourArray.length; l  )
            testFourSum  = scoreFourArray[l];
        test4Calculation = (double) testFourSum / 5;

        System.out.println("The average for test one is: "   test1Calculation);
        System.out.println("The average for test two is: "   test2Calculation);
        System.out.println("The average for test three is: "   test3Calculation);
        System.out.println("The average for test four is: "   test4Calculation);

        Scanner studentSearch = new Scanner(System.in);
        System.out.println("Enter student name : ");
        String foundStudent = studentSearch.nextLine();
        boolean found = Arrays.stream(studentNameArray).anyMatch(t -> t.equals(foundStudent));
        if (found) {
            index  ;
            System.out.println(foundStudent   " is found.");

            //menu loop
            do {
                //displayed user options
                System.out.println("1. To find score for first test");
                System.out.println("2. To find score for second test");
                System.out.println("3. To find score for third test");
                System.out.println("4. To find score for fourth test");

                //menu choices
                Scanner keyboard = new Scanner(System.in);
                System.out.print("\nEnter your choice: ");
                choice = keyboard.next();

                if (choice.equals("1")) {
                    int  score= scoreOneArray[index];

                    System.out.println(score);
                    checker = -1;
                } else if (choice.equals("2")) {
                    int  score= scoreTwoArray[index];
                    System.out.println(score);
                    checker = -1;
                } else if (choice.equals("3")) {
                    int  score= scoreThreeArray[index];
                    System.out.println(score);
                    checker = -1;
                } else if (choice.equals("4")) {
                    int  score= scoreFourArray[index];
                    System.out.println(score);
                    checker = -1;
                } else {
                    //Error message
                    System.out.println("invalid choice");
                }
            }
            while (checker != -1);
        } // End of Menu Method
        else {
            System.out.println(foundStudent   " is not found.");}
        

        students.close();
        TestOne.close();
        TestTwo.close();
        TestThree.close();
        TestFour.close();

    }
}

Calculations(GradeBook):

import java.util.ArrayList;

public class GradeBook {

    private char[] letterGrade = {'A', 'B', 'C', 'D', 'F'};
    private ArrayList<String> names = new ArrayList<>();
    private double [][] scores = new double[5][4];

    public GradeBook(ArrayList<String> studentNames, double[][] studentScores){
        this.names = studentNames;

        for (int i = 0; i < 5; i  ){
            for (int j = 0; j < 4; j  ){
                scores [i][j] = studentScores[i][j];
            }
        }
    }
    public  String getName(int studentIndex){
        return names.get(studentIndex);
    }
    public double getAverage(int studentIndex){
        double total = 0;

        for (int i = 0; i < 4; i  ){
            total  = scores[studentIndex][i];
        }
        return (total / 4);
    }
    public char getLetterGrade(double avgScore){

        if (avgScore >= 90 && avgScore <= 100){
            return letterGrade[0];
        }
        else if (avgScore >= 80 && avgScore <= 89){
            return letterGrade[1];
        }
        else if (avgScore >= 70 && avgScore <= 79){
            return letterGrade[2];
        }
        else if (avgScore >= 60 && avgScore <= 69){
            return letterGrade[3];
        }
        else if (avgScore >= 0 && avgScore <= 59){
            return letterGrade[4];
        }
        return ' ';
    }
    public void getStudent(){

        for (int i = 0; i < names.size(); i  ){

            System.out.println("\nStudent #"   (i 1)
             "\n\t\tName: "   names.get(i)
             "\n\t\tAverage: "   getAverage(i)   "%"
             "\n\t\tLetter Grade: "   getLetterGrade(getAverage(i))
             "\n\n");
        }

    }
} 

CodePudding user response:

I don't understand how much of what's going on in GradeBook relates to what you're doing in your main function. I see how in your main you're coming up with a single score based on the user's selection of a student and a test number. But once you have this user and score, I don't see how that matches up with the data in the double[][] studentScores table contained in GradeBook. What is that data? Where does it come from?

Your code in main seems to have a significant problem. index will always be 1 by the time it's used. Its value is not affected by what is entered as a student name. I think you mean for it to be. Also, I don't understand how the single integer score you come up with in main matches up with the avgScore accepted by the GradeBook. But ignoring all of that...

It seems like you'd have just a single GradeBook, right? So I think you'd instantiate just a single instance of it, and then you could use it to look up the student's name and to calculate the grade based on the student's score. Assuming that index matched up with the names list in GradeBook, and you somehow computed an averageScore, that would look something like this...

public class Main {

    public static void main(String[] args) throws IOException {
        ...
         
        GradeBook gradeBook = new GradeBook(...);
        
        ...

        while (...) { 
            index = ...
            ...
            averageScore = ...
            ...
            studentName = gradeBook.getName(index);
            grade = gradeBook. getLetterGrade(averageScore);
        
            System.out.println(String.format("Student: %s. Grade: %s", studentName, grade));
    }

The other use case I can see is that you'd calculate somehow calculate the studentScores table from the data you read in main, and then you could create a GradeBook with that to have it display all of that information. That would look like this...

studentScores = ...
...
GradeBook gradeBook = new GradeBook(studentScores);
gradeBook.getStudent()
  •  Tags:  
  • java
  • Related