#12469: JAVA解答,請指教


spadegun (spadegun)

學校 : 不指定學校
編號 : 53256
來源 : [220.132.168.12]
最後登入時間 :
2017-07-09 21:20:07
a017. 五則運算 | From: [220.132.168.12] | 發表日期 : 2017-07-27 21:35

import java.util.Scanner;

public class Arithmetic {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s;
while (scanner.hasNext()) {
s = scanner.nextLine();
while (s.contains("(") || s.contains(")")) {
s = s.replace(getBrackets(s), calcBrackets(s));
}
s = calc(calcMDM(s));
System.out.println(s);
}
}

public static String getBrackets(String s) {
return s.substring(s.lastIndexOf("(", s.indexOf(")")), s.indexOf(")") + 1);
}

public static String calcBrackets(String s) {
return calc(calcMDM(getBrackets(s)));
}

public static String calcMDM(String s) {
int i = 0;
while (i < s.length()) {
if (s.charAt(i) == '*' || s.charAt(i) == '/' || s.charAt(i) == '%') {
int start = s.lastIndexOf(" ", i - 2) + 1;
int end = s.indexOf(" ", i + 2);
s = end > 0 ?
s.replace(s.substring(start, end), calc(s.substring(start, end))) :
s.replace(s.substring(start), calc(s.substring(start)));
}
i++;
}
return s;
}

public static String calc(String s) {
int sum = 0;
int i = 0;
String[] sa = s.split(" ");
while (i < sa.length) {
switch (sa[i]) {
case "(":
case ")":
i++;
continue;
case "*":
sum *= Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "/":
sum /= Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "%":
sum %= Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "+":
sum += Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "-":
sum -= Integer.parseInt(sa[i + 1]);
i += 2;
break;
default:
sum += Integer.parseInt(sa[i]);
i++;
break;
}
}
return String.valueOf(sum);
}
}
 
#20656: Re:JAVA解答,請指教


andreea (andreea)

學校 : 國立清華大學
編號 : 114796
來源 : [1.169.102.153]
最後登入時間 :
2021-04-13 11:38:27
a017. 五則運算 | From: [122.117.100.222] | 發表日期 : 2020-02-16 21:45

謝謝您提供的參考解答

 
ZeroJudge Forum