Search code examples
javadrjava

String variable Initialization error


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!


Solution

  • Change

    String functionName;
    

    to

    String functionName = null;