java 由于 Integer.parseInt 而崩溃
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7292169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Crashing due to Integer.parseInt
提问by BGM
I'm trying to import text from a text file which has been generated in another Activity
. The generated text file is made up of a String
ArrayList
which only contains numbers and the other random text generated by Android. When I import the text from the file I'm using a BufferedReader
and readLine()
to get each new number into an Integer
ArrayList
. I'm removing any non-numerical values from the text file and the numbers that are generated in the other Activity are split up by an "\n".
我正在尝试从在另一个Activity
. 生成的文本文件由一个String
ArrayList
仅包含数字的文本和其他由 Android 生成的随机文本组成。当我从文件中导入文本时,我使用 aBufferedReader
并将readLine()
每个新数字放入Integer
ArrayList
. 我正在从文本文件中删除任何非数字值,并且在另一个活动中生成的数字由“\n”分隔。
The problem that I'm facing is that Android crashes when it loads the Activity
. I've narrowed the cause down to Integer.parseInt()
.
我面临的问题是 Android 在加载Activity
. 我已将原因缩小到Integer.parseInt()
.
My code is below:
我的代码如下:
ArrayList<Integer> lines = new ArrayList<Integer>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File file = new File(getFilesDir(), "test_file.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while (br.readLine() != null) {
String text = (br.readLine()).replaceAll("[^0-9]+","").trim();
Integer number = Integer.parseInt(text);
lines.add(number);
}
} catch (IOException e) {
}
TextView tv = (TextView) findViewById(R.id.helptext);
int max = 0, min = 100;
double total = 0;
for (int i = 0; i < lines.size(); i++) {
int number = lines.get(i);
max = Math.max(max, number);
min = Math.min(min, number);
total += number;
}
tv.setText("max = " + max + " min = " + min + " total = "
+ total);
回答by dacwe
Problems:
问题:
When you do
replaceAll("[^0-9]+","")
you can end up with an emptystring causingInteger.parseInt
to throw anNumberFormatException
.You are skipping every other line (your
while
loop condition consumes the first line, the third line and so on...)while (br.readLine() != null) // consumes one line
当你这样做时,
replaceAll("[^0-9]+","")
你可能会得到一个空字符串,导致Integer.parseInt
抛出一个NumberFormatException
.您正在跳过每隔一行(您的
while
循环条件消耗第一行、第三行等等......)while (br.readLine() != null) // consumes one line
Try something like this:
尝试这样的事情:
BufferedReader br = new BufferedReader(new FileReader(file));
String input;
while ((input = br.readLine()) != null) {
String text = input.replaceAll("[^0-9]+","");
if (!text.isEmpty())
lines.add(Integer.parseInt(text));
}
回答by Rohan Kandwal
All the above answers are true but they won't help you if, for some reasons data coming to you isn't an Integer
. eg- Server by mistake sent you user name instead of userId (should be an Integer).
以上所有答案都是正确的,但如果出于某些原因,提供给您的数据不是Integer
. 例如- 服务器错误地向您发送了用户名而不是 userId(应该是整数)。
This might happen so we must always place in checks to prevent it. Otherwise, our app will crash and it won't be a pleasant user experience. So, while converting String
to Integer
, always use a try-catch
block to prevent app crashes. I use following code to prevent app crash due to Integer parsing -
这可能会发生,因此我们必须始终进行检查以防止它发生。否则,我们的应用程序将崩溃并且不会是一个愉快的用户体验。因此,在转换String
为 时Integer
,请始终使用try-catch
块来防止应用程序崩溃。我使用以下代码来防止由于整数解析而导致应用程序崩溃 -
try {
Log.d(TAG, Integer.parseInt(string));
} catch (NumberFormatException e) {
Log.w(TAG, "Key entered isn't Integer");
}
回答by Ricky
Ensure text
isonly numbers in a string, it's likely not. Also you may want to try:
保证text
是唯一的数字字符串中的,很可能不是。您也可能想尝试:
Integer number = Integer.valueOf(text);
instead of:
代替:
Integer number = Integer.parseInt(text);
See:
看:
parseInt() returns primitive integer type (int), whereby valueOf returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.
parseInt() 返回原始整数类型(int),其中valueOf 返回java.lang.Integer,它是整数的对象代表。在某些情况下,您可能需要一个 Integer 对象,而不是原始类型。
Edit: After your comments below, I'd log text
every time in the loop, chances are when it throws the error the log will show the text
variable is empty.
编辑:在您在下面发表评论后,我会text
在每次循环中记录,当它抛出错误时,日志将显示text
变量为空。
回答by Android Killer
If you will give numbers as string like "1234"it will not give any exception or error. But you will give any character or special character, then parse() function will throw exception. So please check carefully there must be some character is passing so it is throwing exception and getting crashed
如果您将数字作为字符串提供,例如“1234”,则不会出现任何异常或错误。但是你会给出任何字符或特殊字符,然后 parse() 函数会抛出异常。所以请仔细检查一定有一些字符正在传递所以它抛出异常并崩溃