现在的位置: 首页 > 综合 > 正文

将整数字符串转换成整数输出(JAVA实现,不能用自带函数)

2017年12月04日 ⁄ 综合 ⁄ 共 475字 ⁄ 字号 评论关闭
/**
	 * @author PLA  
	 * 将整数字符串转换成整数输出
	 */
	public static void main(String[] args) {
		String s = "-1456542";
		change(s);
	}
	public static void change(String s){
		boolean flag = true;
		long num = 0;
		int temp;
		char[] ch = s.toCharArray();
		for(int i=0;i<ch.length;i++){
			if((i==0)&&(ch[i] == '+')){
				flag = true;
			}
			else if((i==0)&&(ch[i] == '-')){
				flag = false;
			}
			else if((ch[i]>='0')&&ch[i]<='9'){
				temp = ch[i]-'0';
				num = num*10 + temp;
			}else{
				System.out.println("Wrong!!!");
				return;
			}
		}
		if(flag==false){
			System.out.println(-num);
		}else{
		System.out.println(num);
		}
	}

抱歉!评论已关闭.