By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,581 Members | 2,023 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,581 IT Pros & Developers. It's quick & easy.

How to fix Unreachable Statements?

P: 4
Expand|Select|Wrap|Line Numbers
  1. import java.util.Random;
  2. import TerminalIO.KeyboardReader;
  3.  public class random
  4.  {
  5.   public static void main(String args[])
  6.   {
  7.   int guess;
  8.   int answer;
  9.   Random generator = new Random();
  10.   KeyboardReader reader = new KeyboardReader(); 
  11.   System.out.print("Enter Guess");
  12.   guess = reader.readInt();
  13.   answer = generator.nextInt(99+1);
  14.   while(guess!=answer){
  15.   if (guess<answer)
  16.   System.out.print("The answer is higher");
  17.   break;
  18.   if (guess>answer)
  19.   System.out.print("The answer is lower");
  20.   break;
  21.   if (guess==answer)
  22.   System.out.print("Correct!");
  23.   break;}
  24. }
  25. }
  26.  
I keep getting errors on line 18, and 21 anyone who helps, thanks in advance.
Dec 14 '10 #1
Share this Question
Share on Google+
3 Replies


P: 5
The problem is the first break statement always terminates the while loop. Try enclosing the system.out.print statements and the break statements in brackets:

Expand|Select|Wrap|Line Numbers
  1.  if (guess<answer)
  2.   {
  3.   System.out.print("The answer is higher");
  4.   break;
  5.   }
That way, it's executed conditionally, along with the print statement.
Dec 14 '10 #2

P: 4
thank you for the help
Dec 15 '10 #3

P: 1
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.
2 Weeks Ago #4

Post your reply

Sign in to post your reply or Sign up for a free account.