简体   繁体   English

使用用户输入的子字符串切换语句

[英]Switch statement using substring of a user's input

Objective: I am trying to ouput a message based on a user's input. 目标:我正在尝试根据用户的输入输出消息。

Situation: Basically a user will input a few characters like 5r (5 Red) or 8y (8 Yellow). 情况:基本上,用户将输入一些字符,例如5r(5红色)或8y(8黄色)。 The notation expected is a digit first and a character after but it is possible that the user doesn't follow the rule. 期望的表示法是第一个数字,然后是一个字符,但是用户可能不遵循该规则。

I used switch statements (part of the exercise) but the output doesn't give me what I expect 我使用了switch语句(这是练习的一部分),但是输出并没有给出我期望的结果

Code : 代码

        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0,1);
        String secondChar = input.substring(1);
        String answer = "";

        switch(firstChar)
        {
            case "0":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "Zero Blue";
                    case "r":
                        answer = "Zero Red";
                    case "g":
                        answer = "Zero Green";
                    case "y":
                        answer = "Zero Yellow";
                }
            }
            case "1":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "One Blue";
                    case "r":
                        answer = "One Red";
                    case "g":
                        answer = "One Green";
                    case "y":
                        answer = "One Yellow";
                }
            }
           ... other case statements....
           default:
              answer = "not valid";

When the user writes 0b, my output should be "Zero Blue" but currently it is displaying "not valid". 当用户写入0b时,我的输出应为“零蓝色”,但当前显示为“无效”。 Why? 为什么?

As @markspace mentioned you were missing a break statement. 正如@markspace所提到的,您丢失了break语句。 Here is a short excerpt from Java documentation on switch statements: 这是Java 文档中有关switch语句的简短摘录:

Each break statement terminates the enclosing switch statement. 每个break语句终止封闭的switch语句。 Control flow continues with the first statement following the switch block. 控制流从切换块后的第一条语句继续。 The break statements are necessary because without them, statements in switch blocks fall through. break语句是必需的,因为如果没有它们,则切换块中的语句会失败。

Also I recommend using a dedicated method and for loops for easier debugging. 另外,我建议使用专用方法和for循环以简化调试。

The following code produces the result you want: 以下代码产生所需的结果:

public static String getAnswer() {

        Scanner reader = new Scanner(System.in);
        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0, 1);
        String secondChar = input.substring(1);

        String[] chars = new String[] { "b", "r", "g", "y" };
        String[] answers1 = new String[] { "Zero Blue", "Zero Red", "Zero Green", "Zero Yellow" };
        String[] answers2 = new String[] { "One Blue", "One Red", "One Green", "One Yellow" };

        if ((firstChar.equals("0"))) {
            for (int i = 0; i < chars.length; i++) {
                if (secondChar.equals(chars[i])) {
                    return answers1[i];
                }
            }
        }
        else if ((firstChar.equals("1"))) {
            for (int i = 0; i < chars.length; i++) {
                if (secondChar.equals(chars[i])) {
                    return answers2[i];
                }
            }
        }
        return "not valid";
    }

    public static void main(String[] args) throws IOException {

        System.out.println(getAnswer());
    }

EDIT: In addition to the solution above I would like to offer a more sophisticated one that involves the use of enumerators. 编辑:除上述解决方案外,我想提供一种更复杂的解决方案,其中涉及枚举器的使用。 It should make your code feel more clean and to the point as well as being more modular: 它应该使您的代码更加简洁明了,并且模块化程度更高:

public enum Answer {

    BLUE('b',"Blue"), RED('r',"Red"),
    GREEN('g',"Green"), YELLOW('y',"Yellow");

    private static final String[] prefix = new String[] {"Zero", "One"};

    char letter;
    String name;

    Answer(char letter, String name) {
        this.letter = letter;
        this.name = name;
    }

    public static String getForInput(char input, int index) {

        if (index > prefix.length)
            return "value out of range " + index;

        for (Answer answer : Answer.values()) {
            if (input == answer.letter)
                return prefix[index] + " " + answer.name;
        }
        return "unable to find answer for input " + input;
    }
}

public static String getAnswer() {

    System.out.println("Enter your input: ");
    Scanner reader = new Scanner(System.in);
    String input = reader.nextLine().toLowerCase();
    int number = Integer.valueOf(input.substring(0, 1));
    char letter = input.substring(1).charAt(0);

    return Answer.getForInput(letter, number);

}

I suggest not using swich case at all, use hash maps: 我建议完全不使用夹心大小写,使用哈希映射:

package mypackage;

import java.util.*;

public class MyComputingClass {

    private static Map<Character, String> firstCharMapping;
    private static Map<Character, String> secondCharMapping;

    public static void main(String[] args) {
        initCharMappers();

        System.out.println("Mapping of 0Y : " + mapStuff("0Y"));
        System.out.println("Mapping of 0y : " + mapStuff("0y"));
        System.out.println("Mapping of 0YJ : " + mapStuff("0YJ"));
        System.out.println("Mapping of 2B : " + mapStuff("2B"));
        System.out.println("Mapping of eB : " + mapStuff("eB"));
    }

    private static void initCharMappers() {
        firstCharMapping = new HashMap<>();
        secondCharMapping = new TreeMap<>(Comparator.comparing(Character::toLowerCase));

        firstCharMapping.put('0', "Zero");
        firstCharMapping.put('1', "One");
        firstCharMapping.put('2', "Two");

        secondCharMapping.put('Y', "Yellow");
        secondCharMapping.put('B', "Blue");
        secondCharMapping.put('G', "Green");
    }

    private static String mapStuff(String str) {
        String INVALID_INPUT = "Invalid input";
        if (!str.matches("\\d[a-zA-Z]")) {
            return INVALID_INPUT;
        }

        Character firstChar = str.toCharArray()[0];
        Character secondChar = str.toCharArray()[1];

        if (!firstCharMapping.containsKey(firstChar) || !secondCharMapping.containsKey(secondChar)) {
            return INVALID_INPUT;
        }

        return firstCharMapping.get(firstChar) + " " + secondCharMapping.get(secondChar);
    }
}

Output : 输出:

Mapping of 0Y : Zero Yellow
Mapping of 0y : Zero Yellow
Mapping of 0YJ : Invalid input
Mapping of 2B : Two Blue
Mapping of eB : Invalid input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM