英文:
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 )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论