且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文本文件中解析数字

更新时间:2023-01-17 16:04:48

,您需要在catch块中放入一个return语句,或者您需要将其余的代码移动到try块内部(如果文件打开失败,即使您发现错误,fileIn.HasNext也会一定因为该文件仍然没有打开)。

我也复制并粘贴了你的代码,并通过调试器运行它,我认为你的第一个for循环是关闭的,作为名称[i]是:

foo// names [i] = st.nextToken();

foo bar//名字的第一次迭代[i] = names [i] ++ st.nextToken();

foo Bar 19.35 //第二次迭代的名字[i] = names [i] ++ st.nextToken();

reals [i] [0]在整数(55)中,值为55.0
然后ints [i] [0]抛出一个异常,因为下一个数字是一个double,而不是一个int。

所以你的for循环应该是:

  for(int k = 0; K< M-5; k)
{
name = name ++ st.nextToken();
}


just wondering what i am doing wrong here. i am trying to read from a file and parse through some data. i keep getting error "java.lang.NumberFormatException" that it can't parse the numbers. I know i use getNextDouble() or get nextInt() but im trying to keep the code as general as i can. Any thoughts would be greatly appreciated. ty.

here is a sample of a line from my text file:

       foo Bar 19.35 55 987.0054 4 

public void readFile(){
        int i=0;
        String line;

        try{
            fileIn = new Scanner(new File("pa1Names.txt"));
        }catch(Exception e){
            System.out.println("Fatal Error: File was not opened");
        }

        while(i<names.length && fileIn.hasNext()){
            line = fileIn.nextLine();
            StringTokenizer st = new StringTokenizer(line);
            int m = st.countTokens();

            names[i] = st.nextToken();

            for (int k = 0; k<m-5; k++)
            {
                names[i] = names[i] + " " + st.nextToken();
            }

            reals[i][0] = Double.parseDouble(st.nextToken());
            ints[i][0]  = Integer.parseInt(st.nextToken());
            reals[i][1] = Double.parseDouble(st.nextToken());
            ints[i][1]  = Integer.parseInt(st.nextToken());

            i++;
        }//end while
        fileIn.close();
    }

In your try/catch block, you need to put in a return statement in the catch block, or you need to move the rest of the code to be inside the try block (if the file open fails, even though you caught the error, the fileIn.HasNext will definitely fail because the file is still not open).

I also copied and pasted your code and ran it through a debugger, I think your first for loop is off, as names[i] is the following:

"foo" //names[i] = st.nextToken();

"foo bar" // first iteration of names[i] = names[i] + " " + st.nextToken();

"foo Bar 19.35" // second iteration of names[i] = names[i] + " " + st.nextToken();

The reals[i][0] then reads in the integer (55), so has a value of 55.0 The ints[i][0] is then throwing an exception because the next number is a double not an int.

So your for loop should be:

            for (int k = 0; k<m-5; k++)
            {
                name = name+ " " + st.nextToken();
            }