Java do循环-字符串无法解析
使用 Java 中程序员定义的方法开发一个简单的掷骰子游戏。因为我知道程序需要至少运行一次,然后询问玩家是否想再次运行,所以我选择使用 do/while 循环。我以前从未使用过,但我相信我设置正确。
我的代码如下,不包括循环中包含的主方法主体以及程序员定义的方法。
do {
// main METHOD BODY ..
String proceed = ui.nextLine();
System.out.print("Would you like to play again (yes/no)? ");
} while (proceed.charAt(0) == 'Y' || proceed.charAt(0) == 'y');
此时我从 Eclipse IDE 得到的是“无法继续进行”。
对发生的事情有什么想法吗?
Working on a simple dice rolling game using programmer defined methods in Java. Since I know the program needs to run at least once and then ask if the player wants to go again, I elected to use a do/while loop. I've never had to use one before, but I believe I set it up right.
My code is as follows, excluding the body of my main method contained within the loop, as well as the programmer defined methods.
do {
// main METHOD BODY ..
String proceed = ui.nextLine();
System.out.print("Would you like to play again (yes/no)? ");
} while (proceed.charAt(0) == 'Y' || proceed.charAt(0) == 'y');
What I get from the Eclipse IDE at this point is "proceed cannot be resolved."
Any ideas as to what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 while 循环中取消引用时,proceed 不在范围内。将 procedure 变量的声明移到 do 之外。
proceed isn't in scope at the time it is being dereferenced in the while loop. Move the declaration of the proceed variable outside of the do.
您需要在
do
之外声明它。当您在
do
中声明它时,其作用域仅在该语句的主体内,并且无法在while
部分解析。You need to declare it outside the
do
.When you declare it inside the
do
, its scope is only within that statement's body, and can't be resolved on thewhile
part.与其最初将其设置为 null,然后再给它一个值,不如将其值定义为“N”,这样另一个出现的编码器就不会暗示与 null 相关的行为并采取相应的行动。该值应该是 2 个值之一... Y 或 N,不要将其初始化为除两个预期值之外的其他值。
您还可以使用其中的方法修改该 while 条件,使其更清晰一些。它更能描述您想要执行的操作,并且您可以对条件进行单元测试。
修改相当于:
其次,在有意剪裁的代码上,确保包含以下内容:
如果您的代码比这多得多,那么在一个地方就太多了。
Rather than setting this to null initially and then giving it a value later, it's better to just define it's value to 'N' so another coder who comes along doesn't imply behavior associated to null and act accordingly. This value should be 1 of 2 things... Y or N, don't initialize it to something other than it's two intended values.
You can also modify that while condition to be a bit cleaner by using a method there. It's more descriptive of what you want to do and you can unit test the condition.
With modifications that amounts to:
Second, on your code that is intentionally snipped, Make sure that consists of something like:
If you have a lot more code than that, it's too much in one spot.