gpt4 book ai didi

java - 帮助打破 if/else 吗?

转载 作者:行者123 更新时间:2023-12-01 15:55:48 26 4
gpt4 key购买 nike

我正在编写一个协议(protocol)类,其中包含很多 if/elses..这是该类:

public class Protocol {
Scanner scan = new Scanner(System.in);
private static final int WAITING = 0;
private static final int SENTREQUEST = 1;
private static final int SENTITEMS = 2;
private static final int ANOTHER = 3;
private static final int CHOICE = 4;
private int choice;

private int state = WAITING;



public String processInput(String theInput) {
String theOutput = null;

if (state == WAITING) {
theOutput = "Do you accept the terms of agreement? Y/N?";
state = SENTREQUEST;
} else if (state == SENTREQUEST) {
if (theInput.equalsIgnoreCase("y")) {

theOutput = ": 1. program file 2. pictures 3. documentation";
state = CHOICE;
} else {
theOutput = "Invalid Input!";
state = SENTITEMS;

}

}
else if (state == CHOICE) {
choice = scan.nextInt();
switch(choice) {
case 1: theOutput = "show something";
break;
case 2: theOutput = "show something";
break;
case 3: theOutput = "show something";
break;
}
}
else if (state == SENTITEMS) {

theOutput = "Want another? (y/n)";
state = ANOTHER;

} else if (state == ANOTHER) {

theOutput = "Do you accept the terms of agreement? Y/N?";

if (theInput.equalsIgnoreCase("y")) {
theOutput ="test";
state = SENTREQUEST;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}

它没有到达 switch case,我确信这是正确突破 if/elses 子句的问题,但我找不到问题。

最佳答案

为了解决类似的问题,一旦我实现了 strategy pattern作为枚举。对于每个策略,您为枚举创建一个新值,将代码封装在枚举方法中:

public enum Strategy {

FIRST_STRATEGY {
public String process(String input) {
// Implementation for first strategy
return null;
}
},

SECOND_STRATEGY {
public String process(String input) {
// Implementation for second strategy
return null;
}

};

public abstract String process(String input);

}

您可以根据您拥有的枚举值应用所选策略,实际上删除 if/else 语句链:

Strategy chosenStrategy = Strategy.FIRST_STRATEGY;
String output = chosenStrategy.process(input);

这是我针对自己的问题应用的解决方案,也许它不是最佳的或更面向对象的解决方案。您必须为您的问题选择正确的解决方案,但我希望我的经验可以有所帮助。

关于java - 帮助打破 if/else 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5078133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com