【问题标题】:Object cannot be converted无法转换对象
【发布时间】:2016-11-07 14:30:29
【问题描述】:

所以我试图从一个同时包含字符串和整数的数组中转换一个数字,但不断收到该错误。如果我尝试解析它,我会得到它无法转换为字符串的错误,如果我尝试直接使用数组变量,我会得到它无法转换为 int.. 这是代码

import java.io.*;
import java.util.*;
import java.lang.*;
import java.*;

public class sav
{
public static void main (String [] args)throws IOException{
   try{
int rows = 0;
//String temp;
int tempint = 0;
Scanner file = new Scanner (new File("sav_duom.txt"));
while (file.hasNextLine())
{
    rows++;
    file.nextLine();
}

file = new Scanner (new File("sav_duom.txt"));
System.out.println(rows);
Object[][] data = new Object[rows][5];
for(int i = 0;i<rows;i++)
{
    String str = file.nextLine();
    String[] tokens= str.split(",");
        int temp = data[i][4];
        //temp = temp.replaceAll("\\W","");
        //tempint = Integer.parseInt(temp);
    for (int j = 0;j<5;j++)
    {

        if(temp > 5)
        {
        data[i][j] = tokens[j]; 
        System.out.print(data[i][j]);
        if(j == 3){
        System.out.print(":");
        } else {
        System.out.print(" ");
        }
        }
    }     
    System.out.print(" \n");
}
file.close();
        }
catch(Exception e)
{
    e.printStackTrace();
}

}
}

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    我收到无法转换为字符串的错误

    您需要转换为不同类型的存储值。

    Stringint 使用Integer.parseInt(String)

    int number = Integer.parseInt("1234");
    

    intString 使用String.valueOf(int)

    String s = String.valueOf(1234); 
    

    另外,根据文件中的数据类型,将 data 数组声明为 int[][]String[][]

    【讨论】:

    • 嗯,我先转换为字符串,然后转换为 int,但现在我收到此错误 java.lang.NumberFormatException: For input string: "null" at java.lang.NumberFormatException.forInputString(Unknown Source) 在 java.lang.Integer.parseInt(Unknown Source) 在 java.lang.Integer.parseInt(Unknown Source) 在 sav.main(sav.java:34)
    • For input string: "null" 表示文件中有一个空字符串...检查您的数据并在更新中读取链接的 API 方法
    • 当我尝试打印出数组元素时,我试图转换,它打印的字符串很好
    猜你喜欢
    • 2011-08-17
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多