1

My problem is that my values i1, i2, and i3 are all showing errors saying the values are not initialized when I try to compile my program. I thought I had given them a value but apparently not. Here is my code, I'm sure it's a quick fix and thank you.

public class Project3

 {
    /**********************************************************************************
 * Method Name: main <br>
 * Method Purpose: To develop a program that prompts the user for test scores and calculates their average and displays their GPA and letter grade.
 * <br>
 *
 * <hr>
 * Date created: 10/16/2013 <br>
 * Date last modified: 10/16/2013 <br>
 * <hr>
 * @param String[] args - Command Line Arguments
 */
    public static void main(String[] args)
    {

     //------------------------------variables--------------------------------  
    int iMenuOption;

    int i1;
    int i2;
    int i3;

    Scanner kb = new Scanner(System.in);
    String strName;

    myInfo();

    createWelcomeMessage();

    System.out.print("\n\n");

    pressEnterToContinue();

    System.out.print("\n");

    clearScreen();

    iMenuOption = menuOption();

    while (!(iMenuOption == '1'))
        {
        System.out.print("\nUser option 1 to enter test scores\n\n");

        pressEnterToContinue();
        clearScreen();

        iMenuOption = menuOption();
        }


    if (iMenuOption == '1')
        {
            i1 = testScore();
            i2 = testScore();
            i3 = testScore();
        }
    else if (iMenuOption == '2')
        {
            System.out.print("Score 1: " + i1);
            System.out.print("Score 2: " + i2);
            System.out.print("Score 3: " + i3);
        }

    }


    public static double calcAverage(int i1, int i2, int i3)
    {
    double dAverage;

    Scanner kb = new Scanner(System.in);

    dAverage = ((i1 + i2 + i3)/3.0);

    return dAverage;
    }   //end calcAverage



    public static void createWelcomeMessage()
    {
        Scanner kb = new Scanner(System.in);

        String strName;
        System.out.print("What's your user name? ");
        strName = kb.nextLine();

        System.out.print("\nHello, " + strName + " this program is made to calculate the" +
        " averages of given test scores, display your letter grade, and the GPA of the scores.");






    }

    public static void pressEnterToContinue()
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("\t Press Enter to Continue \n ");
        keyboard.nextLine();

    }           //end pressEnterToContinue


    public static void clearScreen()    
    {
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

    }           //end clearScreen

    public static int testScore()
    {
        int iTestScore;

        Scanner kb = new Scanner(System.in);


        System.out.print("Enter a test score: ");
        iTestScore = kb.nextInt();



        return (iTestScore);
    }

    public static int menuOption()
    {
        Scanner kb = new Scanner(System.in);

        String strInput;
        int iMenuOption;


        System.out.println("\n        Menu Options");

        System.out.println("\t----------------------");
        System.out.println("\t1. Enter Test Scores");
        System.out.println("\t2. Display Test Scores");
        System.out.println("\t3. Display Average");
        System.out.println("\t4. Display Letter Grade");
        System.out.println("\t5. Display GPA");
        System.out.println("\t6. Exit Program");
        System.out.println("\t----------------------");

        System.out.print("Select one of the options: ");

        strInput = kb.nextLine();
        iMenuOption = strInput.charAt(0);

        while (!(iMenuOption == '1' || iMenuOption == '2' || iMenuOption == '3' || iMenuOption == '4' || iMenuOption == '5' || iMenuOption == '6'))
        {
            System.out.println("Invalid selection");



    enter code here

    System.out.print("Select one of the options: ");



    enter code here

        strInput = kb.nextLine();
            iMenuOption = strInput.charAt(0);
        }`enter code here`









        return iMenuOption;


    }



    public static void myInfo()
    {
        String strName = "\t\tBob";         //My name
        String strClass = "\t\tCSCI ";              //The class info
        String strDate = "\t\t9/18/13";                     //The program's date
        String strAssignment = "\tQuiz4";                   //The assignment name

        System.out.println("Author:\t\t" + strName);
        System.out.println("Class:\t\t" + strClass);
        System.out.println("Date:\t\t" + strDate);
        System.out.println("Assignment:\t\t" + strAssignment);


    }

    public static char letterGrade(double dAverage)
    {
        char cLetterGrade;

        if (dAverage >= 90 && dAverage <= 100)
        {
        cLetterGrade = 'A';
        }
        else if (dAverage >= 80 && dAverage < 90)
        {
        cLetterGrade = 'B';
        }
        else if (dAverage >= 70 && dAverage < 80)
        {
        cLetterGrade = 'C';
        }
        else if (dAverage >= 60 && dAverage < 70)
        {
        cLetterGrade = 'D';
        }
        else
        {
        cLetterGrade = 'F';
        }
        return cLetterGrade;






    }
}
Flexo
  • 87,323
  • 22
  • 191
  • 272
  • intialize these int i1; int i2; int i3; with some value.. hopefully. – Rat-a-tat-a-tat Ratatouille Oct 22 '13 at 04:58
  • 1
    Well, you *haven't* given them a value on a *provable execution path* (the compiler - without any runtime data - needs to tell that an assignment *must occur* before a local variable is read). So fix it (trivially by assigning a default value when they are declared). Namely, the `if` in which the variables are assigned *might not* be entered before the code execution path that attempts to use the variables. Remember, the *compiler must be able to prove that assignment will occur before usage* - and the program is compiled a long time before the while loop ever runs or the user enters data. – user2864740 Oct 22 '13 at 05:00

2 Answers2

3

Your issue is that you haven't forced the user to select option 1 from the menu before option 2. So as far as the compiler is concerned, the "option 2" block might well run first; and in this instance, you would be using the three variables, and they indeed would not have been initialised.

I think you need to re-think the flow of your program, to decide whether it actually makes sense to allow your user to do this.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
2

Inside a method you must initialize the variables,

int i1 = 0;
int i2 = 2;
int i3 = 3;

You can define class/instance variables without initializing, but for local variables (inside method) you must initialized them

public class{
 String globalVariable; //this is ok defining with out initializing

 public void method1(){
   int localVariable = 1; //you should initialize these if you are using them inside
 }

}
Isuru Gunawardana
  • 2,847
  • 6
  • 28
  • 60
  • I thought I did initialize them locally by using the i1 = testScore(); method. – user2864535 Oct 22 '13 at 05:08
  • @user2864535 No you can't just define local variables without initializing them inside a method. – Isuru Gunawardana Oct 22 '13 at 05:10
  • @user2864535 you can get an idea about these in http://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java – Isuru Gunawardana Oct 22 '13 at 05:12
  • @user2864535 please be generous mark an answer as the answer if you find it correct or up vote the answers if you find it helpful. – Isuru Gunawardana Oct 22 '13 at 05:16
  • This is kind of a misleading answer. There's no such thing as global variables in Java - I guess you mean instance variables or static variables. And there is no compulsion to initialise variables that are declared locally - only that if you try to use them in an expression, you must have initialised them first. You might have some logic in there that causes all uses of the variables to be skipped in certain circumstances, in which case it makes sense not to initialise them. Itsmeisuru - I don't think you should use words like "can't", when what you really mean is "usually shouldn't". – Dawood ibn Kareem Oct 22 '13 at 06:38
  • @DavidWallace : Not only instance variables but class variables also can be defined without initializing... yeah you are right there's no global variables in java, but I want to explain the problem with the meaningful words and that's why I gave him a link with all the details. I edited the answer and remove misleading words – Isuru Gunawardana Oct 22 '13 at 06:44
  • 1
    Yeah, what you call "class variables" are what I called "static variables" in my previous comment. So thanks for making this change. But you've still got the issue that you're telling the OP that they MUST initialise their local variables; and that's just not true. Please remember that you're teaching beginners here - in my opinion, it's important not to teach them stuff that's wrong. – Dawood ibn Kareem Oct 22 '13 at 06:57
  • @DavidWallace You are correct and thank you for explaining the mistakes I have done. – Isuru Gunawardana Oct 22 '13 at 08:31