//Guess a number between 1 and 1000 //Java how to program, 5/e, Exercise 6.34-35 import javax.swing.*; import java.awt.*; import java.awt.event.*; publicclass NumberGuessGame extends JApplet implements ActionListener { int number,random,counter=0; JLabel guessLabel; JTextField guessField; publicvoid init() { Container container=getContentPane(); container.setLayout(new FlowLayout()); guessLabel=new JLabel("Guess a number between 1 and 1000:"); container.add(guessLabel); guessField=new JTextField(10); container.add(guessField); guessField.addActionListener(this); random=(int)(1+1000*Math.random()); } publicvoid actionPerformed (ActionEvent event) { number=Integer.parseInt(guessField.getText()); while(number!=random) { number=Integer.parseInt(guessField.getText()); if(number>random) { showStatus("Too high. Try again."); guessField.setText(""); counter++; } else { showStatus("Too low. Try again"); guessField.setText(""); counter++; } } showStatus("Congratulations! You guessed the number!"); System.out.println("You have tried "+counter+"times in total!"); if(counter<=10) System.out.println("Either you know the secret or you got lucky!"); if(counter==10) System.out.println("Aha! You know the secret!"); elseif(counter>10) System.out.println("You should be able to do better!"); } }
//Guess a number between 1 and 1000//Java how to program, 5/e, Exercise 6.34-35import javax.swing.*;import java.awt.*;import java.awt.event.*;public class NumberGuessGame extends JApplet implements