2017-09-06 112 views
-2

我想建立一个简单的程序,将继续这样做,直到满足某些条件。在这种情况下,无论是对还是错。我一直在玩这个游戏一段时间,但我仍然无法按照我的需要去实现它。我使用while循环不正确吗?

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); 
    } 
} 
+0

鸵鸟政策比较==改用string1.equals字符串(字符串2) –

回答

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); 
    } 
}