so I have an assignment that I need to use a switch statement to identify a marker for range of random values The question is like this:
Using switch statements, please identify the different ranges. Hence, follow the suggested markers:
“o” for numbers between (0,5];
“x” for numbers between (5, 10];
“s” for numbers between (10, 15];
“*” for numbers bigger than 15;
import java.util.*; public class Problem01 { public static void main(String[] args) { //create random integer Random ran = new Random(); int sum = 0; for (int i = 1; i <= 10; i++ ) { int random = ran.nextInt(20); //Printing the random number System.out.print("Number " + "(" + random + "): "); //Loop to print markers for(int j = 1; j <= random; j++) { //I don't know how to use the switch statement at this point, I tried everything and nothing work } } } }
I have searched on the internet a lot but none of the way work, can you guys help me, thanks a lot
Advertisement
Answer
You can do the following:
import java.util.*; public class Problem01 { public static void main(String[] args) { //create random integer Random ran = new Random(); int sum = 0; for (int i = 1; i <= 10; i++ ) { int random = ran.nextInt(20); //Printing the random number System.out.print("Number " + "(" + random + "): "); switch ((random-1)/5) { case 0: System.out.println("o"); break; case 1: System.out.println("x"); break; case 2: System.out.println("s"); break; default: //to handle case where the number is bigger than 15 System.out.println("*"); break; } } } }
I’m not sure why you needed the inner loop.
This is the generated output for the above program.
Number (1): o Number (10): x Number (5): o Number (13): s Number (9): x Number (13): s Number (6): x Number (16): * Number (16): * Number (10): x
edit: There is no direct way to use custom ranges with switch statements. This has been answered here