2017-09-06 110 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); 
    } 
}