我在使用do while循环不正确吗?

时间:2017-09-06 10:55:41

标签: java

我正在尝试构建一个简单的程序,该程序将继续执行,直到满足某个条件。在这种情况下,无论是真还是假。我已经玩了一段时间,但我仍然无法按照我的意愿去工作。

import java.util.Scanner;

public class oddeven {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a number: ");

        int num = scan.nextInt();
        boolean play = true;
        String restart = " ";

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

            System.out.println(
               "Would you like to pick another number? (Type 'yes' or 'no')");

            restart = scan.nextLine();

            if(restart == "yes") {
                System.out.println("Enter a number: ");
                play = true;
            } else {
                System.out.println("Thanks for playing!");
                play = false;
            }
        }
        while(play == true);
    }
}

1 个答案:

答案 0 :(得分:0)

以下是您要执行的操作的代码。你一直在做3到4个错误,看看代码,你就会明白。

你还应该看到这个链接

What's the difference between next() and nextLine() methods from Scanner class?

http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html

import java.util.Scanner;

class test {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        boolean play = true;
        do {
        System.out.println("Enter a number: ");
        int num = Integer.valueOf(scan.next());
        String restart = " ";
            if ((num % 2) == 0) {
                System.out.println("That number is even!");
            }
            else {
                System.out.println("That number is odd!");
            }
            System.out.println("Would you like to pick another number? (Type 'yes' or 'no')");
            restart = scan.next();
            if (restart.equalsIgnoreCase("yes")) {
                play = true;
            }
            else {
                System.out.println("Thanks for playing!");
                play = false;
            }
        } while (play == true);
    }
}