代码
import java.util.*;
public class Main2 {
static HashMap<Character,Integer> pr = new HashMap<Character, Integer>();
static Stack<Integer> num;
static Stack<Character> op;
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
pr.put('+', 1);
pr.put('-', 1);
pr.put('x', 2);
pr.put('/', 2);
in.nextLine();
for(int i=0; i<n; i++) {
num = new Stack<Integer>();
op = new Stack<Character>();
String str = in.nextLine();
for(int j=0; j<str.length(); j++) {
char c = str.charAt(j);
if(c>='0' && c<='9') num.push(c-'0');
else {
if(op.size()!=0 && pr.get(op.peek())>=pr.get(c)) eval();
op.push(c);
}
}
while(op.size()!= 0) eval();
if(num.peek() == 24)
System.out.println("Yes");
else
System.out.println("No");
}
}
public static void eval() {
int b = num.pop();
int a = num.pop();
char c = op.pop();
int x;
if(c == '-') x = a - b;
else if(c == '+') x = a + b;
else if(c == 'x') x = a * b;
else x = a / b;
num.push(x);
}
}
注意
一、java中Stack的使用:
定义及初始化: Stack<Integer> num = new Stack<Integer>();
使用:
1.入栈:int a = num.push()
。
2.出栈:int b = num.pop()
3.取值:int c = num.peek()
, 取栈顶值,不出栈。
二、java写算法时,需自定义函数注意事项:
其实和c++类似,自定义函数和main并列就行,只是因为java写习惯了,就容易写main函数里边,注意就行。且记得加static修饰符。
如果自定义函数和主函数有公共变量,需要将变量定义为全局变量。
三、java中Scanner输入多行字符串注意事项:
类似此题,先输入一个n,接着输入n行字符串
错误示范:
int n = in.nextInt();
while(n -- != 0){
String s = in.nextLine();
}
因为int n = in.nextInt();
这句代码,只输入了n,而忽略了/n;当第一次读入字符串时会将/n读入,导致最后一次没能读入字符串。
正确案例
int n = Integer.parseInt(in.nextLine());
for(int i=0;i<n;i++){
String str = in.nextLine();
}
将第一个n用行读取的方式,然后取出数字n,即可正常输入。或者最上代码,添加一个in.nextLine()
跳过/n;
四、(额外的)字符串与数字的相互转换:
字符串转数字:int n = Integer.parseInt(str);
或者int n = Integer.valueOf(str)
double n = Double.parseDouble(str);
数字转字符串:
int i = 11;
String s = i + ""; // 方法一
String s = String.valueOf(i); // 方法二
String s = Integer.toString(i); // 方法三