0

I am doing a leave management system for my assignment. And this is the part where I ask user to save their registration. First, I use do...while(true) loop to ask for their info like name, ID , department, etc. I start with adding a boolean regErr = false before the do...while(true) loop and it has no problem.

Then I continue with this part and add a boolean saveReg. But I have no idea why it shows error and says its unreachable code. If I add the boolean saveReg inside do...while loop also doesn't work. I really need your help to figure out what's the problem. Thank you in advance and have a nice day!

        boolean saveReg;    //the boolean that is unreachable code
        
        do{
            :
            :
        }while(true);
    
    if(saveReg){
        try(PrintWriter rW = new ....)){
            :
            :
        }catch(IOException err){
            err.printStackTrace();
        }
    }
    else{
        System.out.println("Fail to register.");
    }
Yeoh Joey
  • 1
  • 4

1 Answers1

0

That is because of your first code, while(true) will make it run for infinite times so code below this is unreachable. Use below code -

 boolean regErr = false;

 do{
     regErr = false;

     System.out.print("Name: ");
                  :
                  :

  }while(regErr )
  • 1
    Correct, Either use variable inside loop or use break statement like - boolean regErr = false; do{ regErr = false; break; System.out.print("Name: "); }while(true ); System.out.println("1"); –  Jan 06 '23 at 05:29
  • Ah I see, no wonder... My problem solved by using the code above. I really appreciate your help. – Yeoh Joey Jan 06 '23 at 08:41