我的布尔值为什么是不可达的代码和编译错误?

huangapple go评论63阅读模式
英文:

Why my boolean is unreachable code and compilation error?

问题

以下是您要翻译的部分:

我正在为我的作业做一个请假管理系统。这是我要求用户保存他们的注册信息的部分。首先,我使用了do...while(true)循环来询问他们的信息,如姓名、ID、部门等。在do...while(true)循环之前,我开始添加了一个boolean regErr = false,没有问题。

然后,我继续添加了一个boolean saveReg 的部分。但我不知道为什么它显示错误并说它是不可达的代码。如果我将boolean saveReg 添加到do...while循环中也不起作用。我真的需要您的帮助来找出问题所在。提前谢谢您,祝您有一个愉快的一天!

boolean saveReg; //不可达的代码部分

do{
:
:
}while(true);

if(saveReg){
try(PrintWriter rW = new ....)){
:
:
}catch(IOException err){
err.printStackTrace();
}
}
else{
System.out.println("注册失败。");
}

英文:

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.");
	}

答案1

得分: 0

这是因为你的第一段代码,while(true) 会使它无限运行,所以此代码下面的部分无法访问。请使用以下代码 -

boolean regErr = false;

do {
    regErr = false;

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

} while (regErr);
英文:

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 )

huangapple
  • 本文由 发表于 2023年1月6日 12:25:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定