JAVA: Hi, I need help with my program. I need to edit my code so that everytime
ID: 3671481 • Letter: J
Question
JAVA: Hi, I need help with my program. I need to edit my code so that everytime it runs the program generates a random array of numbers and sorts them instead of what I currently have. Any help is much appreciated, thanks
Here is my code:
import java.awt.Graphics;
import java.applet.Applet;
public class Sort extends Applet{
int a[] = { 55, 25, 66, 45, 8, 10, 12, 89, 68, 37 };
int b[] = { 55, 25, 66, 45, 8, 10, 12, 89, 68, 37 };
public void paint(Graphics g){
print(g,"Data items in original orer",a,25,25);
sort(b);
//sort(a);
print(g,"Data items in ascending order",b,25,55);
//print(g,"Data items in ascending order",a,25,85);
}
//Bubble Sort Function: Sets an array into ascending order
public void sort(int a[]){
int i,j,t;
for(i=0; i< b.length; i++){
for(j=0; j< b.length ; j++){
if (b[i] < b[j]){
t = b[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
public void print(Graphics g, String head, int b[], int x, int y){
g.drawString(head,x,y);
x+=15;
y+=15;
for(int i=0;i<b.length;i++){
g.drawString(String.valueOf(b[i]),x,y);
x+=20;
}
}
}
Explanation / Answer
import java.awt.Graphics;
import java.applet.Applet;
public class Sort extends Applet{
int a[] = new int[];
int b[] = new int[];
generateRandomNumbers();
public void generateRandomNumbers() {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<100; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<10; i++) {
a[i]=list.get(i);
b[i]=a[i]
}
}
public void paint(Graphics g){
print(g,"Data items in original orer",a,25,25);
sort(b);
//sort(a);
print(g,"Data items in ascending order",b,25,55);
//print(g,"Data items in ascending order",a,25,85);
}
//Bubble Sort Function: Sets an array into ascending order
public void sort(int a[]){
int i,j,t;
for(i=0; i< b.length; i++){
for(j=0; j< b.length ; j++){
if (b[i] < b[j]){
t = b[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
public void print(Graphics g, String head, int b[], int x, int y){
g.drawString(head,x,y);
x+=15;
y+=15;
for(int i=0;i<b.length;i++){
g.drawString(String.valueOf(b[i]),x,y);
x+=20;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.