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

2024-02-29

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

}

最后的变量“play”没有被测试。我是否超出了范围或其他什么?我到处寻找答案,但似乎找不到解决我的错误的方法。谢谢。


play必须在 do-while 循环之前声明才能处于 do-while 循环的范围内while健康)状况。

String play = "";
do {
    ...
    play = prompt.next();
} while(play.equalsIgnoreCase("yes"));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

while 循环不工作吗? (找不到变量) 的相关文章

随机推荐