java.util
中的随机类创建一个程序,以生成1到100之间的数字。这是我到目前为止所做的:
import java.util.Random;
import javax.swing.JOptionPane;
public class GuessANumber3 {
public static int TARGET = 0;
public static void main(String[] args) {
Random R = new Random();
TARGET = R.nextInt(100);
String guessString;
int guess;
int count = 0;
int bestScore = 0;
System.out.println(TARGET);
do {
// read in a number from user as a string
guessString = JOptionPane.showInputDialog("Enter first integer");
// convert number from type String to type int
guess = Integer.parseInt(guessString);
count++;
if (guess > TARGET) {
JOptionPane.showMessageDialog(null, "Your guess is too high", "Hint",
JOptionPane.PLAIN_MESSAGE);
} else {
if (guess < TARGET) {
JOptionPane.showMessageDialog(null, "Your guess is too low", "Hint",
JOptionPane.PLAIN_MESSAGE);
}
}
System.out.println(count);
if (count == 6)
break;
} while (guess != TARGET);
if (guess == TARGET)
JOptionPane.showMessageDialog(null, "You found it with " + count + "guesses.",
"Congratulations!", JOptionPane.PLAIN_MESSAGE);
else
JOptionPane.showMessageDialog(null, "You have reached the maximum attempts in this go",
"Attention", JOptionPane.PLAIN_MESSAGE);
if (count < bestScore)
bestScore = count;
}
}
任何人都可以帮我解决第3和第4部分吗?
答案 0 :(得分:2)
我建议通过oop设计解决问题。根据您的要求,
所以在伪代码中
class User
{
String name;
}
class Session
{
User user;
Game currentGame;
void startNextGame()
{
//create game, when game end, ask to continue
}
}
class Game
{
int ties = 6;
int number;
Game()
{
Random random = new Random();
number = random.nextInt();
}
void play()
{
for( int i = 0; i < tries; ++i )
{
Attempt attempt = new Attempt( number );
attempt.try();
if( attempt.guessed() )
{
//Show guessed
return;
}
}
//show unguessed
}
}
class Attempt()
{
int expectedNumber;
Attempt( int number )
{
expectedNumber = number;
}
void try()
{
//get guess
}
boolean guessed()
{
//return result of try
}
}
void main()
{
//getUser
User user;
//if I have session for user, getSession, if not create and store ex. map
//start next game in session
}