while while循环不工作? (找不到变量)

时间:2016-02-21 14:34:07

标签: java

我遇到问题,我的do while循环没有找到我的变量来测试条件是否为真。这是我的代码:

import java.util.Scanner;
public class Loops
{
  public static void main(String[] args){
   System.out.println("Programmer: Jarred Sylvester");
   System.out.println("Course:     COSC 111, Winter 2016");
   System.out.println("Lab#:        5");
   System.out.println("Due date:    Feb. 18, 2016");

   Scanner prompt = new Scanner(System.in);

   do{ 
   System.out.print("\nEnter a whole number: ");

   int num = prompt.nextInt();

   if(num % 2 == 0){
       System.out.println(num + " is even");
    }
   else{
       System.out.println(num + " is odd");

    }

    System.out.println("\nNumbers from 1 through " +num+ " are:");
    for(int counter = 1; counter <= num; counter++){
        System.out.print(counter + "    ");
    }

    int counter = 1;
    System.out.println("\n\nSquare of odd numbers from 1 through " + num + " are:");
    while(counter <= num){
        if(counter % 2 ==1){

        System.out.print((counter * counter)+ "     ");

        }
        counter++;
    }

    counter = 1;int sum =0;
    System.out.println("\n\nSum of even numbers from 1 through " +num+ " is:");
    while(counter <= num){

        if(counter % 2 == 0){
             sum+=counter;


        }

        counter++;
    }
     System.out.print(sum);


    System.out.println("\n\nNumbers from 1 through "+num+"(5 numbers per line):");
    for(int count = 1; count <= num; count++){
        System.out.print(count + "      ");

        if(count % 5 == 0){
            System.out.print("\n");

        }


    }

    System.out.println("\n\nDo it again, yes(or no)?");

  String play = prompt.next();
}while(play.equalsIgnoreCase("yes"));
}

}

变量&#34; play&#34;最后还没有接受测试。我是否超出范围或什么?我到处寻找答案,但似乎无法找到我的错误的解决方案。谢谢。

3 个答案:

答案 0 :(得分:4)

必须在do-while循环之前声明

play才能处于while条件的范围内。

String play = "";
do {
    ...
    play = prompt.next();
} while(play.equalsIgnoreCase("yes"));

答案 1 :(得分:0)

由于您使用do{} while()循环,因此超出了范围。当java到达do语句时,它会跳到while语句以确保它返回true。直到那之后它才会在中间看到代码。

如果您使用while(condition){body}语句,则更容易看到变量的正确范围,因为变量位于顶部,我们自然希望首先执行的代码为。< / p>

所以我会使用如上所述的while循环,你必须在该行之前声明play变量。希望有效:)

答案 2 :(得分:0)

不是将play声明为局部变量,而是将其声明为类级变量。

String play;
do {
    ...
    play = prompt.next();
} while(play.equalsIgnoreCase("yes"));