英文:
Create a marker for range with switch statement in java
问题
import java.util.*;
public class Problem01 {
    public static void main(String[] args) {
        // 创建随机整数
        Random ran = new Random();
        int sum = 0;
        for (int i = 1; i <= 10; i++ ) {
            int random = ran.nextInt(20);
            // 打印随机数
            System.out.print("数字 (" + random + "): ");
            // 使用switch语句打印标记
            switch (random) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    System.out.println("o");
                    break;
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                    System.out.println("x");
                    break;
                case 11:
                case 12:
                case 13:
                case 14:
                case 15:
                    System.out.println("s");
                    break;
                default:
                    System.out.println("*");
            }
        }
    }
}
英文:
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
答案1
得分: 1
你可以执行以下操作:
import java.util.*;
public class Problem01 {
    public static void main(String[] args) {
        //创建随机整数
        Random ran = new Random();
        int sum = 0;
        for (int i = 1; i <= 10; i++ ) {
            int random = ran.nextInt(20);
            //打印随机数
            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: //处理数字大于15的情况
                    System.out.println("*");
                    break;
            }
        }
    }
}
我不确定你为什么需要内部循环。
这是上述程序的生成输出。
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
编辑:在switch语句中没有直接使用自定义范围的方法。这个问题在这里得到了解答:链接
英文:
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
答案2
得分: 1
最直接的解决方案就是为每个数字使用多个`case`选项:
String s = "$";
switch (j) {
    case 1: case 2: case 3: case 4: case 5:
        s = "x"; break;
    case 6: case 7: case 8: case 9: case 10:
        s = "o"; break;
    case 11: case 12: case 13: case 14: case 15:
        s = "s"; break;
    default:
        s = "*"; break;
}
System.out.println(s);
更高级的版本是通过将输入参数除以5(减1后纠正)来减少`case`的数量:
switch ((j - 1) / 5) {
    case 0:
        s = "x"; break;
    case 1:
        s = "o"; break;
    case 2:
        s = "s"; break;
    default:
        s = "*"; break;
}
也可以完全通过使用`%`运算符计算数组中的索引来摆脱`switch`:
public static final String[] OPTS = {"X", "O", "S", "*"};
//...
String s = j < 20 ? OPTS[(j - 1) / 5 % OPTS.length] : OPTS[OPTS.length - 1];
**更新**
另一个解决方法是使用类/枚举来封装范围(虽然内部仍需使用`if`):
public enum RANGE {
    X(0, 5, "x"),
    O(5, 10, "o"),
    S(10, 15, "s"),
    OTHER(0, -1, "*");
    private final int min;
    private final int max;
    private final String sym;
    RANGE(int min, int max, String sym) {
        this.min = min;
        this.max = max;
        this.sym = sym;
    }
        
    public String getSym() {return sym; }
    static RANGE from(int n) {
        return Arrays.stream(RANGE.values())
                     .filter(r -> r.min < n && n <= r.max)
                     .findFirst().orElse(RANGE.OTHER);
    }
}
// 实际上,switch似乎是多余的:
switch(RANGE.from(j)) {
    case X: // 做些什么
        break;
    // ...
    OTHER:
    default:
        // 未找到范围
        break;
}
英文:
The most straightforward solution would be just to use multiple case options for each number:
String s = "$";
switch (j) {
    case 1: case 2: case 3: case 4: case 5:
        s = "x"; break;
    case 6: case 7: case 8: case 9: case 10:
        s = "o"; break;
    case 11: case 12: case 13: case 14: case 15:
        s = "s"; break;
    default:
        s = "*"; break;
}
System.out.println(x);
A better advanced version is to divide the input parameter by 5 (correct by 1) to reduce the number of cases:
switch ((j - 1) / 5) {
    case 0:
        s = "x"; break;
    case 1:
        s = "o"; break;
    case 2:
        s = "s"; break;
    default:
        s = "*"; break;
}
Also it's possible to get rid of switch completely by calculating an index in the array using % operator:
public static final String[] OPTS = {"X", "O", "S", "*"};
//...
String s = j < 20 ? OPTS[(j - 1) / 5 % OPTS.length] : OPTS[OPTS.length - 1];
Update
Another workaround could be to use a class/enum wrapper for the range (though it would be using if inside):
public enum RANGE {
    X(0, 5, "x"),
    O(5, 10, "o"),
    S(10, 15, "s"),
    OTHER(0, -1, "*");
    private final int min;
    private final int max;
    private final String sym;
    RANGE(int min, int max, String sym) {
        this.min = min;
        this.max = max;
        this.sym = sym;
    }
        
    public String getSym() {return sym; }
    static RANGE from(int n) {
        return Arrays.stream(RANGE.values())
                     .filter(r -> r.min < n && n <= r.max)
                     .findFirst().orElse(RANGE.OTHER);
    }
}
// actually, switch seems redundant:
switch(RANGE.from(j)) {
    case X: // do something
        break;
    // ...
    OTHER:
    default:
        // no range found
        break;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论