Java简单猜测游戏GameZone

时间:2016-11-26 16:17:11

标签: java

试图让它运行并向用户询问他们的猜测存在问题,如果它太低,则说明太低,或太高或正确。然后说明数字是多少。这是我到目前为止的代码。

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

非常感谢任何帮助!

2 个答案:

答案 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!");
    }

你们首先检查用户数是否太高,如果是,那么它会检查用户数是否正确或者是否太低但是只有当数字太高时才会运行代码。

答案 1 :(得分:0)

你的if-else结构不对。我想这就是你想要的:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer
    If Integer.TryParse(TextBox2.Text, i) Then
        i += 1
    Else
        i = 0
    End If
    TextBox2.Text = i.ToString()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim i As Integer
    If Integer.TryParse(TextBox2.Text, i) Then
        i -= 1
    Else
        i = 0
    End If
    TextBox2.Text = i.ToString()
End Sub