简体   繁体   English

涉及字符串比较的Java程序优化

[英]Java Program Optimization Involving String Comparison

So, I made this simple program which tests two string values (representative of two individual primary colours) for difference and type in order to determine the colour of the resultant mixture. 因此,我制作了一个简单的程序,该程序测试两个字符串值(代表两种单独的原色)的区别和类型,以确定所得混合物的颜色。

/**
 * A program that prompts the user to enter the names of two different primary colors to create a mixture.
 * 
 * @author A. Mackey
 * @version 1.0
 */
import java.util.*;
public class ColourMixer {
    public static void main(String [] args) {
        colourMixer();
    }

    public static void colourMixer() {
        Scanner in = new Scanner(System.in);
        String colourOne = "";
        String colourTwo = "";

        System.out.println("You are mixing two different primary colours.");

        System.out.print("Enter your first colour: ");
        colourOne = in.nextLine();

        System.out.print("Enter your second colour: ");
        colourTwo = in.nextLine();

        if((colourOne.equalsIgnoreCase("red") || colourOne.equalsIgnoreCase("blue") ) && (colourTwo.equalsIgnoreCase("blue") || colourTwo.equalsIgnoreCase("red") && !(colourOne.equalsIgnoreCase(colourTwo)))) {
            System.out.println("Your colour combination creates purple!");
        } else if ((colourOne.equalsIgnoreCase("red") || colourOne.equalsIgnoreCase("yellow") ) && (colourTwo.equalsIgnoreCase("yellow") || colourTwo.equalsIgnoreCase("red") && !(colourOne.equalsIgnoreCase(colourTwo)))) {
            System.out.println("Your colour combination creates orange!");
        } else if ((colourOne.equalsIgnoreCase("blue") || colourOne.equalsIgnoreCase("yellow") ) && (colourTwo.equalsIgnoreCase("yellow") || colourTwo.equalsIgnoreCase("blue") && !(colourOne.equalsIgnoreCase(colourTwo)))) {
            System.out.println("Your colour combination creates green!");
        } else
            System.out.println("You have not entered two different primary colours.");
    }
}

It functions exactly as intended, with no observable issues. 它的功能完全符合预期,没有明显的问题。

However, it feels clunky and excessive in its logic. 但是,它在逻辑上感到笨拙和过度。

I'm curious if this algorithm could be improved. 我很好奇这个算法是否可以改进。

Maybe some booleans to remove the repetitions. 也许一些布尔值删除重复项。

boolean isRed = colourOne.equalsIgnoreCase("red") || colourTwo.equalsIgnoreCase("red") ;
boolean isBlue =  colourOne.equalsIgnoreCase("blue") || colourTwo.equalsIgnoreCase("blue") ;

if (isRed && isBlue){
   // ...
} else if (isRed && isYellow) {
  // ...

You could put the input Strings (in my case AS lowercase string ) into a Set and could call Sets contains. 您可以将输入字符串(在我的情况下为AS小写字符串)放入Set中,并可以调用Sets contains。

If setContains(red) --> check if contains yellow or blue. 如果setContains(red)->检查是否包含黄色或蓝色。 Now you can choose seither setContains(blue) or setContains(yellow) and test if one of the other colours is present because by doing it this way the combination of the colour doesnt matter and all possible cases are tested. 现在您可以选择setContains(blue)或setContains(yellow)并测试是否存在其他一种颜色,因为通过这种方式,颜色的组合无关紧要,并且测试了所有可能的情况。 yellow and blue will be the same as blue and yellow. 黄色和蓝色将与蓝色和黄色相同。

Set<String> set = new HashSet<String>();
set.add(colourOne.toLowerCase());
set.add(colourTwo.toLowerCase());

if(set.contains("red")){
    if(set.contains("blue")){
        //return purple
    }
    if(set.contains("yellow"){
        //returnorange
    }
}
if(set.contains("yellow")){
    if(set.contains("blue"){
        //return green
    }
}
//unidentified colour

Another option that is available is for you to store them in a list. 可用的另一个选项是将它们存储在列表中。 You can then check if a colour is in the list. 然后,您可以检查列表中是否有颜色。

For example 例如

String colourOne = "blue";
String colourTwo = "red";

List<String> colours= new ArrayList<String>(2);
colours.add(colourOne);
colours.add(colourTwo);


if((colours.contains("red") && colours.contains("blue")
    System.out.println("Your colour combination creates purple!");
etc

This looks like the perfect place to use enums. 这看起来像是使用枚举的理想场所。

enum COLOR{
  RED,GREEN,BLUE,BLACK,WHITE; //etc.
}

And then you could use a method to convert from user input string to colors: 然后,您可以使用一种方法将用户输入的字符串转换为颜色:

public static final COLOR convertToColor(final String input){
    try{
        return COLOR.valueOf(input.toUpperCase());
    }catch(IllegalArgumentException e){
       //invalid color, handle it properly
       System.out.println(input + " is not a valid color !! Enter a new valid color this time!!");
       return null;
    }
}

public static void colourMixer() {
    Scanner in = new Scanner(System.in);
    COLOR color1;
    COLOR color2;

    System.out.print("Enter your first colour: ");
    do{
       color1 = convertToColor(in.nextLine());
    }while( color1 == null);

    System.out.print("Enter your second colour: ");
    do{
       color2 = convertToColor(in.nextLine());
    }while( color2 == null);

    if(COLOR.RED.equals(color1) && COLOR.BLUE.equals(color2)){
          System.out.println("Your colour combination creates purple!");
    }else if(COLOR.RED.equals(color1) && COLOR.YELLOW.equals(color2)){
           System.out.println("Your colour combination creates orange!");
    }//....


}

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

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