How to fix Unreachable Statements?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Charles Sherman
    New Member
    • Dec 2010
    • 4

    How to fix Unreachable Statements?

    Code:
    import java.util.Random;
    import TerminalIO.KeyboardReader;
     public class random
     {
      public static void main(String args[])
      {
      int guess;
      int answer;
      Random generator = new Random();
      KeyboardReader reader = new KeyboardReader(); 
      System.out.print("Enter Guess");
      guess = reader.readInt();
      answer = generator.nextInt(99+1);
      while(guess!=answer){
      if (guess<answer)
      System.out.print("The answer is higher");
      break;
      if (guess>answer)
      System.out.print("The answer is lower");
      break;
      if (guess==answer)
      System.out.print("Correct!");
      break;}
    }
    }
    I keep getting errors on line 18, and 21 anyone who helps, thanks in advance.
  • Lucas McCarthy
    New Member
    • Dec 2010
    • 5

    #2
    The problem is the first break statement always terminates the while loop. Try enclosing the system.out.prin t statements and the break statements in brackets:

    Code:
     if (guess<answer)
      {
      System.out.print("The answer is higher");
      break;
      }
    That way, it's executed conditionally, along with the print statement.

    Comment

    • Charles Sherman
      New Member
      • Dec 2010
      • 4

      #3
      thank you for the help

      Comment

      • creigelde
        New Member
        • Nov 2019
        • 1

        #4
        It is a compile-time error if a statement cannot be executed because it is unreachable. This means that the control flow of your program can't get to that statement, but you assume that they would be. The compiler analyzes the flow, and reports these statements to you as error messages. It is a reliable indicators of logical error in your program.
        Last edited by Rabbit; Nov 26 '19, 05:32 PM. Reason: External link removed

        Comment

        Working...