instanceof关键字用来检测变量类型但是你这里全是字符串,所以用正则来实现就容易多了
public class Test {
public static void main(String[] args) {
String[] arry = {"12","+","4","h"};
String numReg = "^\\d+$";
String strReg = "^[a-zA-Z]+$";
String opReg = "^(\\+|-|\\*|/)+$";
String[] reg = {numReg,strReg,opReg};
String[] msg = {"Integer","Invalid String","Operator"};
for(int i=0;i
for(int j=0;j
System.out.println(temp+" "+msg[j]);
}
}
}
}
}
双层循环就搞定的东西就别谈算法了
建hashmap
key是类型(Integer,Operator)
value是正则表达式("^-?[1-9]\\d*$" ,"[\+\-\*/]")
被拆开的每个子串遍历hash,符合正则表达式输出key,都不符合输出Invalid String,搞定。
楼上的代码有问题,string的正则表达式根本不对h4+12这种字符串根本匹配不出来,应该用排除法来判断,,不属于数字和操作符的就是字符串
public static void main(String args[]) {
Map map = new HashMap();
map.put("Integer", "^-?[1-9]\\d*$");
map.put("Operator", "[\\+\\-\\*/]");
String[] aaa = "12 + 4 h12+".split(" ");
for (int i = 0; i < aaa.length; i++) {
boolean valid=true;
for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
String val = (String) map.get(key);
Pattern p = Pattern.compile(val);
Matcher m = p.matcher(aaa[i]);
if (m.matches()) {
System.out.println(aaa[i]+" : "+key);
valid=false;
break;
}
}
if(valid){
System.out.println(aaa[i]+" : "+"Invalid String");
}
}
}
public class Test {
public static void main(String[] args) {
String[] str = "12 + 4 h".split(" ");
Vector
for(String s : str) {
if(oper.contians(s)) {
//运算符
continus;
}
try {
Double.parseDouble(s);
//数字
} catch(NumberFormatException e) {
//字符串
}
}
}
}
楼主这个操作的主要意图是什么,好让我们想个好算法