未解决的编译问题:对于Integer类型,未定义方法parseInt(String)

时间:2016-03-19 20:09:16

标签: java compiler-errors undefined parseint

为什么它不喜欢parseInt?如何解决?

import java.lang.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.List;
import java.lang.*;

public class Table {

static class Data
{
    private String name = "";
    private int num = 0;

    public Data(String name, int num)
    {
        this.name = name;
        this.num = num;
    }

    public String getName()
    {
        return name;
    }

    public int getNum()
    {
        return num;
    }

    public String toString()
    {
        return name + " " + num;
    }
  }



   public static void main(String[] args) throws IOException 
  {

    List<Data> table  = new ArrayList<Data>();

    try
    {
        String filename= ""C:\\input.txt";
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String line = reader.readLine();

        while(line != null)
        {
            String[] tokens = line.split("[ ]+");

            String tempname = tokens[0];
            int tempnum = Integer.parseInt(tokens[1]);

            Data temp = new Data(tempname,tempnum);

            table.add(temp);
            line = reader.readLine();
        }
        reader.close();
    }
    catch(FileNotFoundException n)
    {
        System.out.println("file not found");
    }
    catch(IOException a)
    {
        a.printStackTrace();
    }

    for(Data n:table)
    {
        System.out.println(n);
    }

       }

    }
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method parseInt(String) is undefined for the type Integer

at Table.main(Table.java:58)

1 个答案:

答案 0 :(得分:0)

代码中存在两个问题:

  • 删除导入
  

import java.lang。*;

  • 路径周围的引号不正确
  • 我猜你的split()方法的正则表达式是不正确的。因此,假设您的输入文件具有以下格式:

    name[]number
    

    以下内容应该有效:

    public static void main(String[] args) throws IOException {
    
    List<Data> table  = new ArrayList<Data>();
    
    try {
        String filename= "/home/kiflem/input.txt";
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String line = reader.readLine();
    
        while(line != null) {
            String[] tokens = line.split("\\[\\s*\\]+");
            if (tokens != null && tokens.length == 2) {
                String tempname = tokens[0];
                int tempnum = Integer.parseInt(tokens[1]);
                Data temp = new Data(tempname,tempnum);
                table.add(temp);
             }
             line = reader.readLine();
         }
            .............
    
  • 如果您的分隔符是空格,请使用

  

“\\ S +”

作为你的正则表达式。