(int)str.charAt(0)与Integer.parseInt的区别


我定义一个数组:Str = 1234;然后用 int a =(int)str.charAt(0)取得强转Int型的值1;为什么当我用判断语句if(1==a) {System.out.println("恭喜,这个正

确的~!");}  总是不能得出结果,然后我用

int a = Integer.parseInt(str.charAt(0)+"") 然后再判断if(1==a) {System.out.println("恭喜,这个正确的~!");}却能得出结果~


原因:

String 的本质 private final char value[]; 算是一个数组。。。。
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
charAt 就是返回数组中某个元素 就是 char


String str = "1234";
char t = str.charAt(0);
System.out.print((int)t); // 49
char 也是整数类型 只不过输出时会被转换为整数在ASCII码表中对应的符号
如果强转 int,那么输出的就是 ASCII码值了。 就是这里的 49 当然等于 1了

Integer.parseInt 完全是另一回事 接受 String为参数 这个就不多做讨论了




将一下java代码转成c语言:import java.util.; public class Main { public static boolean judge(char c1,char c2) { char ch[] = {'#','+','-','','/','%','(',')'}; int num1 = 0,num2 = 0; for(int i = 0;i <= 7;i ++) { if(ch[i] == c1) num1 = i; if(ch[i] == c2) num2 = i; } if(num1 > num2) return true; return false; } public static int calculation(int t1,int t2,char c) { if(c == '+') return t2 + t1; else if(c == '-') return t2 - t1; else if(c == '*') return t2 * t1; else if(c == '%') return t2 % t1; else return t2 / t1; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); Stack<Integer> stk_int = new Stack<>(); Stack<Character> stk_str = new Stack<>(); int index = 0; stk_str.push('#'); for(int i = 0;i < s.length();i ++) { if(s.charAt(i) < '0' || s.charAt(i) > '9') { if(index != i) stk_int.push(Integer.parseInt(s.substring(index,i))); index = i+1; boolean flag = false; while(flag == false) { if (judge(s.charAt(i),stk_str.peek())) { stk_str.push(s.charAt(i)); if(stk_str.peek() == '(' ) stk_str.push('#'); if( stk_str.peek() == ')') { stk_str.pop(); while(stk_str.peek()!='#') { stk_int.push(calculation(stk_int.pop(),stk_int.pop(),stk_str.pop())); } stk_str.pop(); stk_str.pop(); } flag = true; } else { stk_int.push(calculation(stk_int.pop(),stk_int.pop(),stk_str.pop())); } } } if(index != s.length() && i == s.length()-1) stk_int.push(Integer.parseInt(s.substring(index,s.length()))); } while(!stk_int.isEmpty() && stk_str.peek()!= '#') { stk_int.push(calculation(stk_int.pop(),stk_int.pop(),stk_str.pop())); } System.out.println(stk_int.pop()); } }
05-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值