Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Using a Separate Class

843785Mar 11 2009 — edited Mar 13 2009
Hey, everybody. I'm learning Java through a text and it instructed me to write a class that contains several methods for generating random numbers and characters. It then instructed me to write a class containing a main method that calls one of the methods in this separate class. I know that you can't write two classes in one file, so I would appreciate it if someone could help by telling me how I'm supposed to make this work. Here are the two separate classes:

1  public class RandomCharacter { 
 2    /** Generate a random character between ch1 and ch2 */ 
 3    public static char getRandomCharacter(char ch1, char ch2) { 
 4      return (char)(ch1 + Math.random() * (ch2 - ch1 + 1)); 
 5    } 
 6 
 7    /** Generate a random lowercase letter */ 
 8    public static char getRandomLowerCaseLetter() { 
 9      return getRandomCharacter('a', 'z'); 
10    } 
11 
12    /** Generate a random uppercase letter */ 
13    public static char getRandomUpperCaseLetter() { 
14      return getRandomCharacter('A', 'Z'); 
15    } 
16 
17    /** Generate a random digit character */ 
18    public static char getRandomDigitCharacter() { 
19      return getRandomCharacter('0', '9'); 
20    } 
21 
22    /** Generate a random character */ 
23    public static char getRandomCharacter()  { 
24      return getRandomCharacter('\u0000', '\uFFFF'); 
25    } 
26  }
1  public class TestRandomCharacter { 
 2    /** Main method */ 
 3    public static void main(String args[]) { 
 4      final int NUMBER_OF_CHARS = 175; 
 5      final int CHARS_PER_LINE = 25; 
 6 
 7      // Print random characters between '!' and '~', 25 chars per line 
 8      for (int i = 0; i < NUMBER_OF_CHARS; i++) { 
 9        char ch = RandomCharacter.getRandomLowerCaseLetter() ; 
10        if ((i + 1) % CHARS_PER_LINE == 0) 
11          System.out.println(ch); 
12        else 
13          System.out.print(ch); 
14      } 
15    } 
16  }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 10 2009
Added on Mar 11 2009
16 comments
241 views