2016-11-26 107 views
0

遇到問題試圖讓這個運行並詢問用戶猜測,那麼如果它太低,它說明太低,或太高或正確。然後說明數字是什麼。這是迄今爲止的代碼。Java簡單猜測遊戲GameZone

import javax.swing.JOptionPane; 
public class RandomGuess2 { 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     int random; 

     final int MIN = 1; 
     final int MAX = 10; 

     int userNum; 
     String userInput; 

     userInput = JOptionPane.showInputDialog(null, "Please guess a number between 1 and 10"); 
     random = 1 + (int)(Math.random() * MAX); 
     userNum = Integer.valueOf(userInput); 
     int userDiff = (random - userNum); 

     if (userDiff < 0) { 
      JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH"); 

      if (userDiff > 0) 
       JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW");   
      if (userNum == random) 
       JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!"); 
      else 
       JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!"); 
     } 
    } 
} 

任何幫助將非常感謝!

+0

好的,你的問題是什麼? –

回答

0

它不工作的原因是因爲你的支票是錯誤的,它需要是這樣

if (userNum == random){ 
      JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!"); 
    } 
    else{ 

     if (userDiff < 0) { 
     JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH"); 
     } 
     if (userDiff > 0) 
     { 
      JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW"); 
     } 
     JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!"); 
    } 

你是第一次檢查,看看是否usernum過高,如果是那麼它會檢查查看usernum是否正確或者太低,但是隻有當該數字太高時該代碼纔會運行。

0

您的if-else結構不正確。我想這是你想要的:

if (userDiff < 0) { 
    JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH"); 
} else if (userDiff > 0) { 
    JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW"); 
} 

if (userNum == random) { 
    JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!"); 
} else { 
    JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!"); 
} 
+0

謝謝大家!知道它已修復並更正。我感謝所有的幫助! –