Search code examples
javahelper

Why This Code Give me Error in if Statment


Why give me error in Extra word in if statment only

switch (Class) {
  case 'F':
       value = 30;
       Extra = Weight-value ;
       break ;
  case 'B':
      value = 25 ;
      Extra = Weight - value ;

      break ;

   case 'E':
       value = 20 ;
       Extra = Weight - value ;

       break;
    default  :
        System.out.println("You  Not  Enter The  Right Class ");
}
System.out.println("Extra is " );

if ( Extra >=0 )
{
    Total = Extra * 10 ;
    System.out.println("You Have Extra  weight "+Extra +"And You Should Pay "+Total );

}

else
{
    System.out.println("No  Extra Weight to Pay Your  Weight is   "+Weight);
}

Solution

  • Because you're trying to use the value of Extra, but it's possible that Extra has never been assigned a value (if Class isn't 'F', 'B', or 'C', so the default path through the switch is followed). Before being used, a local variable must definitely be assigned a value.


    I strongly recommend following standard Java naming conventions. Local variables should not start with an uppercase character.