简体   繁体   English

Java中的做时循环

[英]Do-While loop in Java

So, as far as I understand it, a do while loop will always run at least once? 因此,据我了解,do while循环将始终至少运行一次? But if this is the case why do we need to declare and initialise variables outside of the loop? 但是如果是这种情况,为什么我们需要在循环之外声明和初始化变量?

Take for instance the following code: 以下面的代码为例:

    do {

    int a = (int) (Math.random() * 13);
    int b = (int) (Math.random() * 13);
    int c = (int) (Math.random() * 13);
    int d = (int) (Math.random() * 13);

    }

    while (a + b + c + d != 24);

Which will throw a compile error that a, b, c, d may not have been initialised. 这将引发可能尚未初始化a,b,c,d的编译错误。 As I'm a java beginner I'm sure there's a simple reason for this, but I cannot seem to find it?! 因为我是Java初学者,所以我确定有一个简单的原因,但是我似乎找不到它?

Much thanks for any help with this. 非常感谢您对此的任何帮助。

Look up variable scope because that is your problem: you're trying to access variables outside of their declared scope, here the do-while loop, and this cannot be done. 查找变量范围,因为这是您的问题:您正在尝试访问超出其声明范围的变量,这里是do-while循环,但这无法完成。

Note your code will work if you introduce one more variable: 请注意,如果再引入一个变量,您的代码将起作用:

int sum = 0; // scope is *outside* of do-while loop
do {
  int a = (int) (Math.random() * 13);
  int b = (int) (Math.random() * 13);
  int c = (int) (Math.random() * 13);
  int d = (int) (Math.random() * 13);
  sum = a + b + c + d;
} while (sum != 24);

But note that now if you still need to access the a, b, c, and d values, you cannot. 但是请注意,现在如果您仍然需要访问a,b,c和d值,则不能。 To allow this, again, you should declare your variables before the loop. 为此,再次,您应该在循环之前声明变量。

This can be re written like this 可以这样写

int a = (int) (Math.random() * 13);
int b = (int) (Math.random() * 13);
int c = (int) (Math.random() * 13);
int d = (int) (Math.random() * 13);

while (a + b + c + d != 24){
 a = (int) (Math.random() * 13);
 b = (int) (Math.random() * 13);
 c = (int) (Math.random() * 13);
 d = (int) (Math.random() * 13);
//do something
}
do {

    int a = (int) (Math.random() * 13);
    int b = (int) (Math.random() * 13);
    int c = (int) (Math.random() * 13);
    int d = (int) (Math.random() * 13);

    }

    while (a + b + c + d != 24);

This is a scoping issue. 这是一个范围界定问题。 Look at jls 6.3. jls 6.3。 Scope of a Declaration 声明范围

You want to re-write the code as so: 您要这样重写代码:

int a = 0; //I am being explicit here  
int b = 0;
int c = 0;
int d = 0;
 do {

        a = (int) (Math.random() * 13);
        b = (int) (Math.random() * 13);
        c = (int) (Math.random() * 13);
        d = (int) (Math.random() * 13);

        }

        while (a + b + c + d != 24);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM