1. Create a subclass of Random class. Your subclass will have the following meth
ID: 3705834 • Letter: 1
Question
1. Create a subclass of Random class. Your subclass will have the following methods and add one more your own method.
public char nextChar()
public char nextChar(char l, char h)
public int nextSequence(int l, int h)
2. Create a main program to test all the above methods in the subclass. Please refer to the skeleton file(newRandomGenerator_Skeleton.java).
public class newRandomGenerator_Skeleton {
public static void main(String[] args) {
System.out.println();
System.out.println("nextChar():");
for (int i=0; i<5;i++){
char c1 = rand.nextChar();
System.out.println(c1);
}
System.out.println();
System.out.println("nextChar('A','C'):");
for (int i=0; i<5;i++){
char c2 = rand.nextChar('A','C');
System.out.println(c2);
}
System.out.println();
System.out.println("nextChar('Y','C'):");
for (int i=0; i<5;i++){
char c2 = rand.nextChar('Y','C');
System.out.println(c2);
}
System.out.println();
System.out.println("nextSequence(1,6):");
for (int i=0; i<5;i++){
int ns = rand.nextSequence(1,6);
System.out.println(ns);
}
}
}
[Sample Output]
----jGRASP exec: java newRandomGenerator_Skeleton
nextChar():
Z
K
J
U
O
nextChar('A','C'):
C
C
B
C
A
nextChar('Y','C'):
Y
B
Y
A
C
nextSequence(1,6):
2
1
4
5
2
----jGRASP: operation complete.
Explanation / Answer
public char nextChar()
{
Random r = new Random();
int n = r.nextInt()%26;
n=n+65;
char c = (char)n;//converting to char...
//returning char...
return c;
}
public char nextChar(char l, char h)
{
int n = (int)l;
int m = (int)h;
Random r = new Random();
char c;
if(m<n)//h less than l
{
int k = m-65;
int j = 122-l;
int q = k+j;
int rr =r.nextInt()%q+1;
if(rr>k)
c=(char)(122-rr-k);//generating random char between l and h
else c=(char)(65+rr-j);//generating random char between l and h
}
else
{
m = m-n;
int rr = r.nextInt()%m+1;
n=n+rr;
c=(char)n;//generating random char between l and h
}
return c;
}
public int nextSequence(int l, int h)
{
Random r = new Random();
int n = h-l +1 ;
n = r.nextInt()%n+l;//generating random number between l and h
return n;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.