I'm trying to write a little program that would allow the user to first enter a number from 9 to 18, to generate corresponding random numbers (that represent the radius), then to calculate the surface (circle) of each randomly-generated number, and finally to sort the results in descending order.
So far here's my code:
import java.util.Scanner;
import java.math.*;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number from 9 to 18: ");
int num9a18 = input.nextInt();
if (num9a18 < 9 || num9a18 > 18) {
System.out.println("This number is invalid!");
}
int num;
for (int i = 0; i < num9a18; i++) {
num = randomInt(1, 6);
System.out.print(num + " ");
}
}
public static int randomInt(int small, int big) {
double PI = 3.141592564;
int results = ((int) (Math.random() * (big - small + 1)) + small);
return results*results*PI;
}
}
Can you give me some tips because I'm kind of stuck here.
Your program will have compilation error due to int
- double
inconsistency
Modified your program to fix that, as well as the one that you probably is looking for.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number from 9 to 18: ");
int num9a18 = input.nextInt();
if (num9a18 < 9 || num9a18 > 18) {
System.out.println("This number is invalid!");
}
double result;
List<Double> results = new ArrayList<Double>();
for (int i = 0; i < num9a18; i++) {
result = resultFromRandomRadius(1, 6);
results.add(result);
}
System.out.println("................SORTING.................");
Collections.sort(results);
for (double res : results) {
System.out.println(res);
}
System.out.println("..........................................");
System.out.println("................REVERSING.................");
Collections.reverse(results);
for (double res : results) {
System.out.println(res);
}
}
public static double resultFromRandomRadius(int small, int big) {
double PI = 3.141592564;
int results = ((int) (Math.random() * (big - small + 1)) + small);
return results * results * PI;
}
}
Note: I'm making use of auto-boxing feature supported since Java 1.5
Update: Updated the code to demonstrate reverse() as well
Output:
Enter a number from 9 to 18:
10
................SORTING.................
3.141592564
3.141592564
12.566370256
12.566370256
28.274333076
78.5398141
78.5398141
78.5398141
113.097332304
113.097332304
.......................................... ................REVERSING.................
113.097332304
113.097332304
78.5398141
78.5398141
78.5398141
28.274333076
12.566370256
12.566370256
3.141592564
3.141592564