java解析分数
我目前的目标是解析分数并创建不合适的分数。 例如:
1_1/3+5/3
应该以同样的方式进入控制台
4/3+5/3
有人能告诉我我走的方向对吗?我应该关注什么
import java.util.Scanner;
public class FracCalc {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them.");
boolean isTrue = true;
String in = "";
while(isTrue) {
in = input.nextLine();
if (in.equals("quit")) {
System.out.println("Thanks for running FracCalc!");
isTrue = false;
}else{
System.out.println("You asked me to compute" + in);
}
}
}
public static void parse(String in){
int underscore = in.indexOf("_");
int slash = in.lastIndexOf("/");
String wholenumber = in.substring(0, underscore);
String numerator = in.substring(underscore + 1,slash);
String denominator = in.substring(slash + 1);
if (underscore<0 & slash<0) {
in = wholenumber;
} else if (underscore<0 & slash>0) {
in = in;
} else if (underscore>0 & slash>0) {
} else if (underscore>0 & slash<0) {
in = "Error";
}
}
}
# 1 楼答案
我会一个字符一个字符地解析字符串。遍历字符串,如果当前字符是数字,则将其附加到名为“currentNumber”的StringBuffer中。如果你当前的角色不是一个数字,你需要决定怎么做。如果是下划线,则知道currentNumber变量中的值是整数部分。然后可以将其存储在单独的变量中,并清除currentNumber缓冲区。如果当前字符是斜杠字符,那么currentNumber中的值就是分数的分子。如果当前字符是空格字符,则可以忽略它。如果它是一个“+”或“-”,你就会知道你的currentNumber变量中有你的分数分母。然后还应将符号作为“运算符”存储在单独的变量中。有很多方法可以实现这一点。例如,你可以有这样的逻辑:“如果我的分子中有一个有效值,而分母中没有,并且我当前查看的字符不是有效的数字字符,那么我已经将分母中的所有数字追加到currentNumber变量中,因此它现在应该包含我的分母。因此,将currentNumber中的值放入我的分母变量中,然后“继续下一个角色”
我希望我没有完全失去你。。。当然,对于你需要做的事情来说,这可能有点太高级了。例如,您没有指定输入字符串的格式,它是否总是与您提到的格式完全相同,或者看起来会有所不同?整数部分可以有两个数字,还是可以一起跳过
我上面描述的方法被称为有限状态机,如果你还没有了解它们,如果你用这种方法交作业,你的老师可能会印象深刻。FSM上有很多阅读材料,所以谷歌是你的朋友
但我想说清楚。你的解决方案看起来也会奏效,只是可能不会那么“动态”