0

For this particular line

for (int p = 0; p<subjects.length; p++) {
    System.out.println(subjects[p] + "\t" + grades[p]);

It basically says "subjects cannot be resolved to a variable". However, almost the same code was used earlier but it works. I'm not sure how can I shorten this code so I'm sorry if it's long. Not sure the standard length of codes to be asked.

import java.util.Scanner;
public class gradingsystempractice{
    public static void main(String[] args) {
 
    
        String user, pass, inpUser, inpPass; //Subjects;
        //String[] subjects = {"CC102", "PE1", "NSTP1", "CC101", "WS101", "MMW", "GEE1", "GEE2"};
                int choice = 0;
                int grades[] = new int[8];
                double sum = 0.0;
        
    
       
        System.out.println("Register account to use Grading System");
        System.out.println("=== CASE SENSITIVE ===");
        
        Scanner scan = new Scanner(System.in);
        System.out.println("\nEnter a username:\t");
        user = scan.nextLine();
        
        Scanner passW = new Scanner(System.in);
        System.out.println("\nEnter a password:\t");
        pass = passW.nextLine();
        
    
        
        Scanner keyboard1 = new Scanner(System.in);
        System.out.println("\nUsername:\t");
        inpUser = keyboard1.nextLine();
        
        Scanner keyboard2 = new Scanner(System.in);
        System.out.println("\nPassword:\t");
        inpPass = keyboard2.nextLine();

        if (inpUser.equals(user) && inpPass.equals(pass)) {
            System.out.println("You have successfully logged in.");
        } else {
            System.out.println("Your username or password is incorrect.");
            
        }
        
        String studentID, studentLN, studentFN, studentMI, courseAndSection;
        
        System.out.println("\nWelcome to Grading System Application\n");
        System.out.println("Please enter the following student credentials to begin");
        System.out.println("\t\tStudent's Profile");
        
        Scanner get = new Scanner(System.in);
        System.out.print("Student #:\n\t");
            studentID = get.nextLine();
        System.out.print("Last name: \n\t");
            studentLN = get.nextLine();
        System.out.print("First name: \n\t");
            studentFN = get.nextLine();
        System.out.print("Middle Initial: \n\t");
            studentMI = get.nextLine();
        System.out.print("Year & Section: \n\t");
            courseAndSection = get.nextLine();
        System.out.print("\n");
        
        do {
            try {
                System.out.println("===========================================");
                System.out.println("Press 1 to Record grades");
                System.out.println("Press 2 to Display all grades");
                System.out.println("Press 3 to Calculate the average grade");
                System.out.println("Press 4 to Calculate the average grade of Midterm and Finalterm to display the Semestral Grade");
                System.out.println("Press 5 to Save and Exit the program");        
                System.out.println("===========================================");
         
                System.out.print("Enter your choice: \t\n");          
                choice = scan.nextInt();
                
                } catch (Exception e) {
                    System.out.println("Input numbers 1,2,3,4, or 5 only.");   
                } 
                if ( choice == 1 ) {
                    int gradeType = 0;

                    Scanner aScanner = new Scanner(System.in);

                    System.out.println("Press 1 to Record for Midterm");
                    System.out.println("Press 2 to Record for Final Term");
                    gradeType = aScanner.nextInt();

                    String[] subjects = { "NSTP", "MMW", "CC102", "Gender and Society", "PAEE", "CC101", "PE", "WS101" };
                    int[] midtermGrades = new int[subjects.length];
                    int[] finalGrades = new int[subjects.length];

                    int[] gradesToCollect;

                        if (gradeType == 1) {
                            gradesToCollect = midtermGrades;
                        } else {
                            gradesToCollect = finalGrades;
                        }

                        collectGrades(subjects, gradesToCollect, aScanner);

                        System.out.println("\n\nThese are the collected grades");
                        System.out.println("Mid  Final");
                        for (int i = 0; i < subjects.length; i++) {
                            System.out.format("%3d  %3d\n", midtermGrades[i], finalGrades[i]);
                        }
                            System.out.println("Enter Grade Successful");
                        }
                
                        if ( choice == 2 ) {
                            System.out.println("Subjects" + "\tGrades");
                            System.out.println("-----------------------------------------");

                            for (int p = 0; p<subjects.length; p++) {
                                System.out.println(subjects[p] + "\t" + grades[p]);
                            }
                        }

                if ( choice == 3 )
                {   
                    System.out.println("Average of grades: " + getAverage(grades));
                    System.out.println();
                }
                if ( choice == 4 ) {
                    System.out.println("Total of grades: " + getSum(grades));
                    System.out.println("Count of grades: " + grades.length);
                    System.out.println("Average of grades: " + getAverage(grades));
                    System.out.println();
                }
                                
        }   
        while ( choice != 5);
        }
     
    public static double getAverage(int[] array)
    {
        int sum = 0;
        for(int i : array) sum += i;
        return ((double) sum)/array.length;
    }
     
    public static double getSum(int[] array)
    {
        int sum = 0;
        for (int i : array) 
        {
         sum += i;
        }
        return sum;
        }

    public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {

        System.out.format("Enter %s subjects and their corresponding grades:",
                subjects.length);
        System.out.println();

        for (int i = 0; i < subjects.length; i++) {
            System.out.format("Enter Grade for %s : ", subjects[i]);
            grades[i] = scn.nextInt();
            if (i == (subjects.length))
                System.out.println();
        }
    }
}

To explain this further, the "if ( choice == 2 )" should display the grades recorded, but apparently it couldn't because it is an error.

  • what error are you talking about? – Stultuske Dec 20 '21 at 12:23
  • 1
    Look up "variable scope" because this is the problem you're having, that the subjects variable is declared within an if block and so is only visible within that block, and you're trying to access it after the if block ends, where it doesn't exist. – Hovercraft Full Of Eels Dec 20 '21 at 12:25
  • 1
    Also, your code indentation is not good, and this is preventing you from seeing which block the variable belongs to. Code formatting matters. A lot. And the rules were not made to force coders to create "pretty" code but rather to encourage coders to create code that is easy for others (and their future selves) to understand and debug, which your code is neither. You will want to strive to learn and follow these formatting rules, including using indentation appropriately. For example, please review [this style guide](https://www.cs.cornell.edu/courses/JavaAndDS/JavaStyle.html#Format). – Hovercraft Full Of Eels Dec 20 '21 at 12:26
  • Other unrelated issues: best to create one single Scanner object based on System.in, and then pass it to where it needs to go. Next, you will want to refactor your code into methods, to help simplify it and make it easier to understand and debug. Next, you will want to learn and use [Java naming conventions](http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java). Variable names should all begin with a lower letter while class names with an upper case letter. Following this will allow us to better understand your code, and would allow you to better understand the code of others. – Hovercraft Full Of Eels Dec 20 '21 at 12:39
  • Speaking of "variable scope", thank you for that. I understood what you're talking about. The string of subjects array was only placed inside the first if statement. The solution is to place "subjects" to where it is accessible everywhere, or basically at the beginning. – Alphamonatric Dec 20 '21 at 14:00
  • And yeah about my code indentation, I actually thought it's pretty organized lol. I guess I haven't watched enough of Java videos. I'm not really sure what "refactoring my code into methods" means tho. I'm not really well-versed with these terms such as methods and objects, as these were not... taught explicitly by my professor. I'll definitely check those out, as well as the other problems you pointed out. Thank you very much! @HovercraftFullOfEels – Alphamonatric Dec 20 '21 at 14:00
  • Your indentation suggests that the `if ( choice == 2 ) {` block is nested within the `if ( choice == 1 ) {` block, which it most definitely is not. Both blocks are on the same level and should have the exact same indentation. – Hovercraft Full Of Eels Dec 20 '21 at 14:03

0 Answers0