字符串和整型之间相互转换

字符串和整型之间相互转换


1、源代码

/**
 * @Title:StringInt.java
 * @Package:com.you.model
 * @Description:字符串和int类型强制转换
 * @Author: 游海东
 * @date: 2014年4月22日 下午10:18:04
 * @Version V1.2.3
 */
package com.you.model;

/**
 * @类名:StringInt
 * @描写叙述:1、将两个字符串强转换成int
 *      2、将两个int类型进行计算
 *      3、将结果转换成字符串 
 * @Author:Administrator
 * @date: 2014年4月22日 下午10:18:04
 */
public class StringInt 
{
	/**
	 * 
	 * @Title : addValue
	 * @Type : StringInt
	 * @date : 2014年4月22日 下午10:20:58
	 * @Description : TODO
	 * @return
	 */
	public static String addValue(String str1,String str2)
	{
		str1 = "2014-04-22"; 
		str2 = "10";
		String str3 = str1.replaceAll("-", " ");
		int val1 = Integer.parseInt(str3);
		int val2 = Integer.parseInt(str2);
		int total = val1 + val2;
		String result = Integer.toString(total);
		return result;
	}

	/**
	 * @Title : main
	 * @Type : StringInt
	 * @date : 2014年4月22日 下午10:18:05
	 * @Description : 调用转换方法
	 * @param args
	 */
	public static void main(String[] args) 
	{
         String str = addValue("2014-02-28","18");
         System.out.println("" + str);
	}

}

2、出现错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "2014 04 22"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:492)
	at java.lang.Integer.parseInt(Integer.java:527)
	at com.you.model.StringInt.addValue(StringInt.java:34)
	at com.you.model.StringInt.main(StringInt.java:50)

3、错误原因

     String str3 = str1.replaceAll("-", " ");后面双引號中间有一个空格


4、正确源代码

/**
 * @Title:StringInt.java
 * @Package:com.you.model
 * @Description:字符串和int类型强制转换
 * @Author: 游海东
 * @date: 2014年4月22日 下午10:18:04
 * @Version V1.2.3
 */
package com.you.model;

/**
 * @类名:StringInt
 * @描写叙述:1、将两个字符串强转换成int
 *      2、将两个int类型进行计算
 *      3、将结果转换成字符串 
 * @Author:Administrator
 * @date: 2014年4月22日 下午10:18:04
 */
public class StringInt 
{
	/**
	 * 
	 * @Title : addValue
	 * @Type : StringInt
	 * @date : 2014年4月22日 下午10:20:58
	 * @Description : 
	 * @return
	 */
	public static String addValue(String str1,String str2)
	{
		/**
		 * 去掉“-”
		 */
		String str3 = str1.replaceAll("-", "");
		/**
		 * 字符串转换成整型
		 */
		int val1 = Integer.parseInt(str3);
		int val2 = Integer.parseInt(str2);
		/**
		 * 两个整型求和
		 */
		int total = val1 + val2;
		/**
		 * 将整型转换为字符串
		 */
		String result = Integer.toString(total);
		/**
		 * 返回结果
		 */
		return result;
	}

	/**
	 * @Title : main
	 * @Type : StringInt
	 * @date : 2014年4月22日 下午10:18:05
	 * @Description : 调用转换方法
	 * @param args
	 */
	public static void main(String[] args) 
	{
		/**
		 * 调用上述方法
		 */
         String str = addValue("2014-02-02","18");
         /**
          * 打印结果
          */
         System.out.println("字符串结果为:" + str);
	}

}

5、结果

字符串结果为:20140220


原文地址:https://www.cnblogs.com/clnchanpin/p/6748727.html