java - 解析文件输入中的数字

标签 java file input

我正在使用扫描仪方法来尝试获取文件输入。问题是我只得到名字和姓氏之后的第一个整数。这是文本文件:

John Doe 12 6 8 15 35 16 17 4 12 54
Mark Doe 16 67 8 12 35 19 78 3 12 101
Johnnie Smarts 20 10 10 20 40 100 20 10 20 100
Frank Noshow
Molly Guess 2 5 6 7 2 4 7 8 9 10

到目前为止我已经完成了这么多代码:

import java.io.*;
import java.util.*;
import static java.lang.Math.*; 
import static java.lang.System.out;

public class StudentTester
{
    public static void main ( String[] args ) throws IOException
    {
        Scanner kb = new Scanner(System.in);
        System.out.println("\tWelcome.. " );
        System.out.println(" Please enter the file name. " );
        String filename = kb.nextLine();
        Scanner fileReader = new Scanner(new File(filename));
        //created a scanner object with a file object.
        //Creat a String array to hold each lince of the file. 
        String [] s = new String [10000]; //prepared for a 100 lines of text.
        int linesOfText = -1;
        int score[] = new int[10];
        while (fileReader.hasNextLine())//while the file has any lines.
        {
            linesOfText++;

            s[linesOfText] = fileReader.nextLine();
            //This places the first line of the file in the s array.
            //System.out.println(s[linesOfText]);//for testing purposes..
        }
        fileReader.close();//close the Scanner.

        for(int i=0;i<=linesOfText;i++){
            Scanner sc = new Scanner(s[i]);
            String fN = sc.next();
            String lN = sc.next();

            if(sc.hasNext()){
                score[i] = sc.nextInt();                 
            }
            else {
                System.out.println(" opps, there is no score here... ");
            }
            Student stu = new Student(fN,lN,score);
            System.out.println(score[i]);
        }
    }
}

最佳答案

这是因为您先执行了 next(),然后执行了 next(),然后执行了 nextInt()

直接替换即可

if (sc.hasNext()) {...} 

while (sc.hasNext()) {...}

关于java - 解析文件输入中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429989/

相关文章:

java - 循环中带有 i+= 的代码不起作用

java - 编写一个使用 float 组和 boolean 值作为参数的 boolean 方法

iOS 将文件行读入数组

file - matlab 垂直串联

input - 如何在 Erlang 中刷新 io 缓冲区?

java - 如何在edittext上创建特定的输入类型?可接受输入罗马数字 M D C X V I

python - 在 Python 和 pandas 中读入 .csv 的通用方法是什么?

java - 使用 AsyncTask,但遇到意外行为

java - 无法隐藏标题栏

java - 如何从 csv 返回特定数据?