我是编码的新手,需要一些这个猜猜我的号码游戏的帮助。任何帮助将不胜感激。如何使用随机数检查用户的输入。此外,如何在游戏结束后让用户再次玩游戏。提前致谢。
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Font;
import java.util.Random;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
//Ryan Kuri
//Mar 3, 2015
//Description:
//
public class GuessMyNumberJOP
{
public static void main(String[] args)
{
Font font1 = new Font ("Cooper Black", Font.PLAIN, 30);
Font font2 = new Font ("Chalkduster", Font.PLAIN, 36);
UIManager.put("OptionPane.messageForeground", Color.WHITE);
UIManager.put("Panel.background", Color.BLACK);
UIManager.put("OptionPane.background", Color.BLACK);
UIManager.put("OptionPane.messageFont", font1);
UIManager.put("TextField.font", font2);
ImageIcon myIcon = new ImageIcon(GuessMyNumberJOP.class.getResource("images.jpg"));
String name1 = (String) JOptionPane.showInputDialog(null,
"Enter Your Name:",
"Number Guess",
JOptionPane.PLAIN_MESSAGE,
myIcon,
null,
"");
AudioClip mySound = Applet.newAudioClip(GuessMyNumberJOP.class.getResource("cheering.wav"));
mySound.play();
JOptionPane.showMessageDialog(null, "Hello, " + name1 + "! ");
Random random = new Random();
Scanner input = new Scanner(System.in);
int min = 1;
int max = 10;
int number = random.nextInt(max - min + 1) + min;
int guesses = 0;
AudioClip explode = Applet.newAudioClip(GuessMyNumberJOP.class.getResource("Copy of explosion-01.wav"));
explode.play();
String num = JOptionPane.showInputDialog("Guess a number between 1 and 10: ");
int guesser = Integer.parseInt(num);
do{
guesses++;
if (guesser > number)
{
JOptionPane.showMessageDialog(null, "My number is less than: " + guesser);
guesser = Integer.parseInt(num);
JOptionPane.showInputDialog("Guess again: ");
}
else if (guesser < number)
{
JOptionPane.showInputDialog(null, "My number is greater than: " + guesser);
guesser = Integer.parseInt(num);
JOptionPane.showInputDialog("Guess again: ");
}
else
JOptionPane.showMessageDialog(null, number + " WAS THE NUMBER --- " + "YOU GOT IT IN " + guesses + " GUESSES");
} while (guesser != number);
System.exit(0);
}
}
答案 0 :(得分:0)
我建议将Random方法分配给变量,然后根据该变量执行IF语句。
例如:
Random rand = new Random();
int randomNumber = rand.nextInt(10)
if randomNumber == 9 {
//Do this
}
else {
}
10是范围的顶部,因此它将选择0-9之间的任意随机数。
希望这有帮助!