/Users/lyon/j4p/src/bookExamples/ch05ControlStructs/RandomNumberGame.java

1    package bookExamples.ch05ControlStructs; 
2     
3    import math.MathUtils; 
4     
5    import javax.swing.*; 
6     
7     
8    public class RandomNumberGame { 
9        public static void main(String args[]) { 
10           RandomNumberGame g = new RandomNumberGame(); 
11           g.hiLo(); 
12       } 
13    
14       static class In { 
15           public static String getString(Object o) { 
16               return JOptionPane.showInputDialog(o); 
17           } 
18    
19           public static int getInt(Object o) { 
20               return Integer.parseInt(getString(o)); 
21           } 
22       } 
23    
24       public void hiLo() { 
25           int r = MathUtils.getRandom(); 
26           String name = In.getString("what is your name?"); 
27           System.out.println("Hello " + name + "\n Welcome to my new game"); 
28           int i = In.getInt("please enter a number from 1 to 100"); 
29           int trys = 1; 
30           System.out.println("you typed a " + i); 
31           while (i != r) { 
32               trys++; 
33               if (i < r) 
34                   i = In.getInt("to low, try again!"); 
35               if (i > r) 
36                   i = In.getInt("to high, try again!"); 
37    
38           } 
39           System.out.println(name 
40                   + " wins after only " 
41                   + trys 
42                   + " tries"); 
43    
44       } 
45   } 
46    
47    
48    
49    
50    
51    
52    
53    
54    
55    
56