2017-09-06 19 views
-2

私は、特定の条件が満たされるまでそれをやり続ける簡単なプログラムを構築しようとしています。この場合、それが真であるか偽であるか。私はしばらくそれを使い続けていましたが、私が望むようにそれを動作させることはまだできません。do 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(string2の)を使用する==で文字列を比較表示されるはずです –

答えて

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); 
    } 
} 
関連する問題