【发布时间】:2019-09-21 10:41:18
【问题描述】:
我们遇到了一个问题,要求使用字母 QDN(Quarter, Dime, Nickel) 来创建一个有限状态机,该状态机仅在它们加到 40 美分时才接受。我已经掌握了使用 IF 语句概念的基础知识。我想知道是否有更简单的方法可以花费更少的时间?
我已经尝试过大量的 if 案例,但使用该方法有很多步骤。
public class FSA2_rpf4961 {
public static void main(String[] args) {
//The program will read in a sequence of strings and test them against a
//FSM. Your strings may not contain blank spaces
System.out.println("Enter string to test or q to terminate");
Scanner in = new Scanner (System.in);
String testString = in.next();
while (!testString.equals("q"))
{
String testOutput = applyFSA2(testString);
System.out.println("For the test string "+testString+
", the FSM output is "+testOutput);
System.out.println("Enter next string to test or q to terminate:");
testString = in.next();
}
in.close();
}
public static String applyFSA(String s) {
String currentOut = "0"; // initial output in s0
String currentState = "s0"; // initial state
int i = 0;
while (i<s.length())
{
//quarter first
if (currentState.equals("s0") && s.charAt(i) == 'q')
{
currentState = "s1";
currentOut += 25; // collect output on move to s1
}
else if (currentState.equals("s1") && s.charAt(i) == 'd') {
currentState = "s2";
currentOut += 10;
}
else if (currentState.equals("s2") && s.charAt(i) == 'n') {
currentState = "s3";
currentOut += 5;
}
else if (currentState.equals("s1") && s.charAt(i) == 'n') {
currentState = "s4";
currentOut += 5;
}
else if (currentState.equals("s4") && s.charAt(i) == 'd') {
currentState = "s3";
currentOut += 10;
}
//dime first
else if (currentState.equals("s0") && s.charAt(i) == 'd')
{
currentState = "s5";
currentOut += 10; // d
}
我们需要它只接受它增加 40 美分。这让我很难理解。
【问题讨论】:
-
没有测试 40 美分,也没有拒绝 40 美分的消息。 currentState 似乎也没有必要,因为没有要求它们按升序排列。在 While 中,只需测试 s.charAt(i) 的 q 或 d 或 n 并添加适当的值。此外,在比较时将每个输入转换为小写。此外,q 不应同时等于 Quit 和 Quarter -- 使用 x 表示 Exit...
标签: if-statement printing count state fsm