String variable Initialization error

125 views Asked by At

I'm receiving an error from my compiler. Anybody have any clues?

import java.util.Scanner;

public class mathProg {

public static void main (String[] args) {

Scanner keyboard = new Scanner(System.in);

int num1, num2, numsum, numdif, numpro, numquo, numexp, cFunction;
String userName; 
String functionName;

System.out.println("Welcome to the calculator!");
System.out.println("What is your name?");
userName = keyboard.nextLine();

System.out.println("Hello, " + userName + "! How can I help you?");
System.out.println("Operable commands are '1' (add), '2' (subtract), ");
System.out.println("'3' (multiply), '4' (divide), and '5' (exponent).");
cFunction = keyboard.nextInt();

switch(cFunction) {
  
  case 1:
    functionName = "addition";
    break;
  case 2:
    functionName = "subtraction";
    break;
  case 3:
    functionName = "multiplication";
    break;
  case 4:
    functionName = "division";
    break;
  case 5:
    functionName = "exponent";
    break;
  default:
    System.out.println("Invalid command.");
    
    
};

System.out.println("You selected " + functionName + ". What number would you like to start with?");

};

};

The error is this:

1 error found:

File: /Volumes/USB20FD/Computer Science/Java/Labs/mathProg/mathProg.java [line: 45]

Error: The local variable functionName may not have been initialized

I'm using DrJava as my IDE, and the Eclipse 0.A48 Compiler. This is for a quick class lab, so all help would be appreciated!

3

There are 3 answers

0
Blub On BEST ANSWER

Change

String functionName;

to

String functionName = null;
0
Stephan On

Set functionName to empty string:

String functionName = "";

If the default case is reached, functionName will never have a chance to have a value.

0
rgettman On

Under the default case, functionName isn't initialized, but it must be initialized prior to using it for the first time. The compiler must ensure that all local variables are initialized in all execution paths before they are used.

Either initialize it to something before the switch, initialize it in the default case, or throw an Exception in the default case.