在java中将字符串转换为整数 [英] Converting string to integer in java

查看:313
本文介绍了在java中将字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sample.java:7:错误:找不到符号

i = Integer.parseInt(s);

^

符号:方法parseInt(String)

位置:类整数



将字符串转换为整数时出错



java版1.8.0_191

javac 1.8.0_161



我的尝试:



sample.java:7: error: cannot find symbol
i=Integer.parseInt(s);
^
symbol: method parseInt(String)
location: class Integer

error has occure while converting string to integer

java version "1.8.0_191"
javac 1.8.0_161

What I have tried:

class sample
{
	public static void main(String args[])
	{
		String s=new String("100");
		int i;
		i=Integer.parseInt(s);
		System.out.print(i);
	}	
}

推荐答案

首先,代码工作得很好,在我的情况下输出为100 ,刚刚在VS Code中尝试过。因此,请显示导致问题的代码。



现在,对于这个问题,这两个错误是不同的,

First off, the code works just fine and the output is 100 in my case, just tried in VS Code. So, show the code that is causing the problem.

Now, for the question, these two errors are different,
sample.java:7: error: cannot find symbol



and,

error has occure while converting string to integer



他们两者都有不同的含义,因此共享它们在两个不同的实例中发生。第一个,主要是指您可能缺少 import 。然而,第二个意味着您传入了正确的字符串值,无法映射到有效整数。你可以做的一些事情,


They both have a different meaning, thus sharing that they occur at 2 different instances. The first one, would mostly mean that you might be missing an import. Whereas, the second one meaning that you has passed in an in correct value of string, that cannot be mapped to a valid integer. A few things you can do,

int value;
try {
   value = Integer.parseInt(s);
} catch (Exception e) {
   // Problem, 
}

这将确保在转换期间出现运行时异常,您的应用程序不会崩溃,而是会有机会呈现屏幕上的友情信息。如果您尝试检查parseInt()函数的文档,您将看到它抛出 NumberFormatException ,这就是您需要查找的内容。



Integer(Java Platform SE 7) [ ^ ]

This will ensure that incase there is a runtime exception during conversion, your app will not crash, instead will be given an opportunity to render a friendly message on the screen. If you try to check the documentation for the parseInt() function, you will see that it throws NumberFormatException, that is what you need to look for.

Integer (Java Platform SE 7 )[^]


import java.lang.Integer;
class sample
{
	public static void main(String args[])
	{
		String s=new String("100");
		int i;
		i=Integer.parseInt(s);
		System.out.print(i);
	}	
}


这篇关于在java中将字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆