不确定为什么代码不能正常工作似乎很好D:
所以这段代码是一个猜谜游戏,因为你可以看到它实现了swing并且出于某种原因它只是不会在eclipse上编译
public class GuessingGame {
public static void main(String[] args)
{
int randomNumber;
randomNumber = (int) (10 * Math.random()) + 1;
Scanner keyboard = new Scanner(System.in);
int guess=0;
int attempts = 0;
GuessingGameGUI game = new GuessingGameGUI( );
game.setVisible(true);
while (guess != randomNumber)
{
try
{
System.out.print("Guess the number from 1-10: ");
attempts++;
guess = keyboard.nextInt();
if (guess < 1 || guess > 10)
throw new BadGuessException();
}
catch (BadGuessException e)
{
System.out.println(e.getMessage());
}
catch (InputMismatchException e)
{
keyboard.next();
System.out.println("Sorry, you entered an invalid number format. ");
}
}
System.out.println("\nYOU GOT IT! (It took " + attempts + " attempt(s))");
}
}
public class GuessingGameGUI extends JFrame
{
public static final int WIDTH = 500;
public static final int HEIGHT = 250;
public GuessingGameGUI()
{
super();
setTitle("Guessing Game");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel north= new JPanel();
add(north, BorderLayout.NORTH);
JLabel lab1 = new JLabel("Guess a number between 1 and 10?");
JPanel center = new JPanel();
add(center, BorderLayout.CENTER);
JTextField userInput = new JTextField();
JButton Guess = new JButton("Guess");
Guess.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel south = new JPanel();
add(south, BorderLayout.SOUTH);
JLabel lab2 = new JLabel();
south.add(lab2);
int guess = 0;
int randomNumber=(int) (10 * Math.random()) + 1;
int attempts = 0;
attempts++;
if (e.getActionCommand().equals("Guess"))
{
if (guess < 1 || guess > 10)
{
lab2.setText("Invalid number");
getContentPane().setBackground(Color.red);
}
else if (guess == randomNumber)
{
lab2.setText("\nYOU GOT IT! (It took " + attempts + "
attempt(s))");
}
else
{
getContentPane().setBackground(Color.GRAY);
lab2.setText("Sorry, try again");
}
}
}
});
//NORTH PANEL
north.add(lab1);
//CENTER PANEL
userInput.setPreferredSize( new Dimension( 200, 25 ) );
setLayout(new FlowLayout());
center.add(userInput);
center.add(Guess);
Container pane = this.getContentPane();
}
}
答案 0 :(得分:1)
关于,
/tmp/java_966Ca2/GuessingGame.java:7: error: cannot find symbol Scanner keyboard = new Scanner(System.in); ^ symbol: class Scanner location: class GuessingGame /tmp/java_966Ca2/GuessingGame.java:7: error: cannot find symbol Scanner keyboard = new Scanner(System.in);
编译器告诉您它无法找到类别,例如Scanner类,因为您还没有导入它们。你必须有像
这样的陈述import java.util.Scanner;
使用此类和其他类。
你有一个方法块,你既可以投掷也可以捕获BadGuessException,这在这种情况下确实没有意义。您需要通过说明和/或与老师讨论来澄清您需要在该代码块中执行的操作,但您当前正在做的事情(除了不创建BadGuessException类之外)是错误的。
答案 1 :(得分:-1)
看起来你错过了BadGuessException。
如果这是学校作业,您可能需要这样的课程:
class BadGuessException extends Exception
{
}