简体   繁体   中英

Variable might not have been initialized when it has been initialized and declared

When it is compiled it says variable secondNumberString might not have been initialized. But I have declared it as a string and initialized it in the secondNumber switch. What am I doing wrong here? I just want to convert secondNumber, say they enter 5, to a string called seondNumberString and have it as five and then display it. It must be using switch.

 /*
Programmer: 
Date: Wednesday, October 8, 2014
Description: A simple calculator
*/

import javax.swing.JOptionPane;     // Imports the JOptionPane class

public class CalculatorStevenHasaka
{
   public static void main(String[] args)
   {
      String input;                 // To temporarily hold the input
      String firstNumberString;     // To hold the string name of the first number
      String secondNumberString;    // To hold the string name of the second number
      String operatorString;        // To hold the string name of the operator
      int firstNumber;              // To hold the first number
      int secondNumber;             // To hold the second number
      int answer;                   // To hold the answer
      char operator;                // To hold the operator

      // Ask the user for a number from 0-9 (The first number)
      input = JOptionPane.showInputDialog(null, "Please enter the first number. \nIt must be from 0 to 9. \nNo decimals, please.", "Calculator v1.0", JOptionPane.QUESTION_MESSAGE);
      // Convert the input to an integer
      firstNumber = Integer.parseInt(input);


      // Validate the input of firstNumber
      while (firstNumber < 0 || firstNumber > 9)
      {
         // Ask the user for a number from 0-9
         input = JOptionPane.showInputDialog(null, "Invalid number! \nIt must be a number from 0 to 9. \nNo decimals, please.", "Invalid Number", JOptionPane.WARNING_MESSAGE);
         // Convert the number to an integer
         firstNumber = Integer.parseInt(input);
      } // End of firstNumber validation


      // Ask the user for an operator
      input = JOptionPane.showInputDialog(null, "Please input an operator. \nYou can use  +,  -,  *,  /,  or  ^", "Calculator v1.0", JOptionPane.QUESTION_MESSAGE);
      // Convert the input to a character
      operator = input.charAt(0);


      // Validate the input of the operator
      while ((operator != '+') && (operator != '-') && (operator != '*') && (operator != '/') && (operator != '^'))
      {
         // Ask the user for an operator
         input = JOptionPane.showInputDialog(null, "Invalid operator! \nYou can only use  +,  -,  *,  /,  or  ^", "Invalid Operator", JOptionPane.WARNING_MESSAGE);
         // Convert the input to a character
         operator = input.charAt(0);
      } // End of operator validation


      // Ask the user for a number from 0-9 (The second number)
      input = JOptionPane.showInputDialog(null, "Please enter the second number. \nIt must be from 0 to 9. \nNo decimals, please.", "Calculator v1.0", JOptionPane.QUESTION_MESSAGE);
      // Convert the number to an integer
      secondNumber = Integer.parseInt(input);


      // Validate the input of secondNumber
      while (secondNumber < 0 || secondNumber > 9)
      {
         //Ask the user for a number from 0-9
         input = JOptionPane.showInputDialog(null, "Invalid number! \nIt must be a number from 0 to 9. \nNo decimals, please.", "Invalid Number", JOptionPane.WARNING_MESSAGE);
         // Convert the number to an integer
         secondNumber = Integer.parseInt(input);
      } // End of secondNumber validation   


      // Convert firstNumber to a string
      switch (firstNumber)
      {
         case 0:
            firstNumberString = "Zero";
            break;
         case 1:
            firstNumberString = "One";
            break;
         case 2:
            firstNumberString = "Two";
            break;
         case 3:
            firstNumberString = "Three";
            break;
         case 4:
            firstNumberString = "Four";
            break;
         case 5:
            firstNumberString = "Five";
            break;
         case 6:
            firstNumberString = "Six";
            break;
         case 7:
            firstNumberString = "Seven";
            break;
         case 8:
            firstNumberString = "Eight";
            break;
         case 9:
            firstNumberString = "Nine";
            break;
         default:
            JOptionPane.showMessageDialog(null, "Invalid input!", "Error", JOptionPane.ERROR_MESSAGE);
      } // End of firstNumber switch


      // Convert secondNumber to a string
      switch (secondNumber)
      {
         case 0:
            secondNumberString = "zero";
            break;
         case 1:
            secondNumberString = "one";
            break;
         case 2:
            secondNumberString = "two";
            break;
         case 3:
            secondNumberString = "three";
            break;
         case 4:
            secondNumberString = "four";
            break;
         case 5:
            secondNumberString = "five";
            break;
         case 6:
            secondNumberString = "six";
            break;
         case 7:
            secondNumberString = "seven";
            break;
         case 8:
            secondNumberString = "eight";
            break;
         case 9:
            secondNumberString = "nine";
            break;
         default:
            JOptionPane.showMessageDialog(null, "Invalid input!", "Error", JOptionPane.ERROR_MESSAGE);
      } // End of secondNumber switch


      // Convert operator to a string and perform the calculations
      if (operator == '+')
      {
         operatorString = "plus";
         answer = firstNumber + secondNumber;
         JOptionPane.showMessageDialog(null, "Blah: " + secondNumberString);
      }
      else if (operator == '-')
      {
         operatorString = "minus";
      }
      else if (operator == '*')
      {
         operatorString = "multiplied by";
      }
      else if (operator == '/')
      {
         operatorString = "divided by";
      }
      else if (operator == '^')
      {
         operatorString = "to the power of";
      }
      else
      {
         JOptionPane.showMessageDialog(null, "Invalid input!", "Error", JOptionPane.ERROR_MESSAGE);
      } // End of operator if/else if/else                    
   } // End of main
} // End of public class                               

But I have declared it as a string and initialized it in the secondNumber switch.

Well, you have if you hit any of the specified cases. But your default case is just:

default:
    JOptionPane.showMessageDialog(null, "Invalid input!", "Error", JOptionPane.ERROR_MESSAGE);

What do you expect the value of secondNumberString to be after that? You should assign a value there - or exit at that point. Given that you're expecting to have validated secondNumber before the switch, I'd throw some sort of RuntimeException instead of showing a message dialog. The compiler will know that at that point you're not going to go ahead and try to use the variable, so it would be definitely assigned after the switch statement.

Note that even though we can tell that you'll never actually hit the default case in the switch statement, the rules for definite assignment and reachability in Java don't cover the idea that the compiler should reason that secondNumber has to be one of 0..9. We need to tell it that we really, really don't expect to get here - and that's why an exception is the best option here.

As an aside, your code would be much cleaner if you'd break up your one enormous method into lots of different methods. Aside from anything else, you then wouldn't need as many local variables. I'd also recommend only declaring variables at the point of their first use, rather than declaring everything at the top. You should also learn to use arrays - which would get rid of the switch statements entirely...

The problem the compiler sees is here:

// Convert secondNumber to a string
  switch (secondNumber)
  {
     case 0:
        secondNumberString = "zero";
        break;
     case 1:
        secondNumberString = "one";
        break;
     case 2:
        secondNumberString = "two";
        break;
     case 3:
        secondNumberString = "three";
        break;
     case 4:
        secondNumberString = "four";
        break;
     case 5:
        secondNumberString = "five";
        break;
     case 6:
        secondNumberString = "six";
        break;
     case 7:
        secondNumberString = "seven";
        break;
     case 8:
        secondNumberString = "eight";
        break;
     case 9:
        secondNumberString = "nine";
        break;
     default:
        JOptionPane.showMessageDialog(null, "Invalid input!", "Error", JOptionPane.ERROR_MESSAGE);
  } // End of secondNumber switch

secondNumber might not be between 0 to 8, Therefore causing secondNumberString will not get a value.

You can set a value at the Default section in order to remove this warning.

your logic seems that it must be between 0 to 8 only so i think you can set at the Default

secondNumberString = null or secondNumberString = ""

Java strictly requires that variables be initialized along EVERY possible path through the code, down to the point where the variable is used.

In the above, secondNumberString is not initialized in the default case of the switch statement.

The compiler isn't smart enough to work out that you've covered every possible value of secondNumber , by way of your while loop (which ensures that secondNumber must be between 0 and 9).

You need to give secondNumberString a default value such as null or "" before the big switch/case to prevent this happening, or alternatively in the default case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM