【问题标题】:Crashing due to Integer.parseInt由于 Integer.parseInt 而崩溃
【发布时间】:2011-11-09 16:01:10
【问题描述】:

我正在尝试从另一个 Activity 中生成的文本文件中导入文本。生成的文本文件由一个String ArrayList 组成,其中仅包含数字和Android 生成的其他随机文本。当我从文件中导入文本时,我使用BufferedReaderreadLine() 将每个新数字放入Integer ArrayList。我正在从文本文件中删除任何非数字值,并且在另一个 Activity 中生成的数字由“\n”分隔。

我面临的问题是 Android 在加载 Activity 时崩溃。我已将原因缩小到Integer.parseInt()

我的代码如下:

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);

【问题讨论】:

    标签: java android arrays parseint


    【解决方案1】:

    以上所有答案都是正确的,但如果由于某些原因提供给您的数据不是Integer,它们将无济于事。例如,服务器错误地向您发送了用户名而不是 userId(应该是整数)。

    这可能会发生,因此我们必须始终进行检查以防止它发生。否则,我们的应用程序将崩溃,这将不会是一个愉快的用户体验。因此,在将String 转换为Integer 时,请始终使用try-catch 块来防止应用程序崩溃。我使用以下代码来防止由于整数解析导致应用程序崩溃 -

    try {
         Log.d(TAG, Integer.parseInt(string));
        } catch (NumberFormatException e) {
          Log.w(TAG, "Key entered isn't Integer");
        }
    

    【讨论】:

      【解决方案2】:

      确保text 字符串中只有数字,很可能不是。你也可以试试:

      Integer number = Integer.valueOf(text);
      

      代替:

      Integer number = Integer.parseInt(text);
      

      见:

      parseInt() 返回原始整数类型 (int),其中 valueOf 返回java.lang.Integer,它是代表的对象 整数。在某些情况下,您可能需要一个整数 对象,而不是原始类型。

      编辑:在下面的 cmets 之后,我会在每次循环中记录 text,当它抛出错误时,日志将显示 text 变量为空。

      【讨论】:

      • 不幸的是,应用程序在尝试您的代码后仍然崩溃。我在其他活动中为文件生成数组列表的方式是:
      • codeString filename = "test_file.txt";文件输出流 fos;尝试 { fos = openFileOutput(文件名, Context.MODE_PRIVATE); ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject(arrayList); out.close(); } catch (FileNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }code ........codearrayList.add(Integer.toString(val[0]) + "\n");code
      • ** 我已经通过在 textView 下打印出 codetextcode 来检查它,并且在使用 replaceAll("[^0-9]* 后字符串中只有数字","") 函数。
      • 你的 text 变量可能包含一个空格,或者在循环中返回空。
      【解决方案3】:

      问题:

      • 当您执行 replaceAll("[^0-9]+","") 时,您可能会得到一个 empty 字符串,导致 Integer.parseInt 抛出 NumberFormatException

      • 您正在跳过每隔一行(您的 while 循环条件会占用第一行、第三行等等...)

        while (br.readLine() != null) // consumes one line
        

      试试这样的:

      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));
      }
      

      【讨论】:

      • 它工作!!!!!!我不得不将 text.isEmpty() 更改为 text.length() == 0 因为我使用的是较旧的 Android API,但它可以工作!非常感谢达克韦!
      • @Arjan - 对此感到抱歉,我确实阅读了有关在 cmets 中回复的帮助,但不小心遗漏了“@”符号。另外,我很抱歉发球台,我真的没想到它会造成这么多麻烦。我花了很长时间试图解决这个问题,当 dacwe 解决了这个问题时我非常高兴,以至于我对他感激不尽。我向你保证它不会再发生了。顺便说一句,我不得不说 stackoverflow 是互联网上最好的(如果不是最好的)代码解决方案网站之一。如果您是帮助设置它的人之一,非常感谢!
      • @BGM,如果您阅读this,dacwe 的 tee 不是问题。最后一点,&lt;nitpicking-mode&gt;Stack Overflow 喜欢在其名称中添加一个空格 ;-)&lt;/nitpicking-mode&gt;。所有这一切:让我们清理一下;我正在删除我的 cmets——欢迎来到 Stack Exchange!
      【解决方案4】:

      如果您将数字作为字符串提供,例如 "1234",它不会给出任何异常或错误。但是你会给任何字符或特殊字符,然后 parse() 函数会抛出异常。所以请仔细检查肯定有一些字符正在传递,所以它抛出异常并崩溃

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-12
        • 2015-09-08
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多