-2

Im getting this error, however Im not entirely sure why, I did declare(line 6) and initialize(line 11) the variable, yet I still get the error. the code is as follows:

public static char ReadChar (String prompt, boolean gui) {
    // Enter (prompt, True) for gui popup, else enter prompt and false

    // set up data and objects
    Scanner input = new Scanner(System.in);
    char data;
    String dataGui, strData;


    // prompt for an input int value
    if (gui == true){

        dataGui = JOptionPane.showInputDialog(null, prompt);
        data = dataGui.charAt(0);

    }

    else {
        System.out.print(prompt);
        strData = input.nextLine();

    }
    return data;

}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115

2 Answers2

1

Assign data varible value. as data is assigned if gui is true but what if data is false. so either u hava to assign in else or at a time of declaration. as to avoid mistake you need assign local varible. Java doesnt forces to initialize instance variable and allows default value but for local variables its the developers call to assign the value.

 char data = 0;
bNd
  • 7,512
  • 7
  • 39
  • 72
0

You have not initialized char.

char data = '\0'; 

or

char data = 0;
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
Shriram
  • 4,343
  • 8
  • 37
  • 64