简体   繁体   English

使用 Scanner 从文件中读取整数的问题

[英]Issue reading integers from file using Scanner

I am having an issue reading integers from an input file using scanner.我在使用扫描仪从输入文件中读取整数时遇到问题。 Here is the bit of code I am having trouble with:这是我遇到问题的代码:

        String path = sc.nextLine(); 
        
        File filename = new File(path);
        
        Scanner reader = null;
        
        reader = new Scanner(filename);
        
        for(int i = 0; i < 4; i++)
        {  
           while(reader.hasNextInt()) 
           {   
               System.out.println(reader.nextLine());
               pid[i] = reader.nextInt();
               arrivaltime[i] = reader.nextInt();
               burstTime[i] = reader.nextInt();
           }      
        } 

The input file I am using contains this information:我正在使用的输入文件包含以下信息:

1 1 1
2 2 2
3 3 3
4 4 4

Using this file, I am trying to make it so that pid[] = [1,2,3,4], arrivaltime[] = [1,2,3,4] and bursttime[] = [1,2,3,4].使用这个文件,我试图使它成为 pid[] = [1,2,3,4],arrivaltime[] = [1,2,3,4] 和 bursttime[] = [1,2,3 ,4]。 However, each of these arrays are instead being shown as [4,0,0,0] and I can't figure out why for the life of me.但是,这些 arrays 中的每一个都显示为 [4,0,0,0] 我无法弄清楚为什么我的生活。 Any help would be appreciated.任何帮助,将不胜感激。

Try this: Read the line first Then split it!试试这个:先阅读该行然后拆分它!

int i = 0
while(reader.hasNextLine()){
   String[] line = reader.nextLine().split(" ");
   pid[i] = Integer.parseInt(line[0]);
   arrivaltime[i] = Integer.parseInt(line[1]);
   burstTime[i] = Integer.parseInt(line[2]);
   i++;
}

When you use scanner.nextLine() the scanner pointer in the file skips first line.当您使用scanner.nextLine()时,文件中的扫描仪指针会跳过第一行。

You can use this if you don't want to print each line or use the other solution with splitting.如果您不想打印每一行或使用其他解决方案进行拆分,则可以使用它。

int i = 0;
while(reader.hasNextInt()) {
    pid[i] = reader.nextInt();
    arrivaltime[i] = reader.nextInt();
    burstTime[i] = reader.nextInt();
    i++;
}

Try This:尝试这个:

    for(int i = 0; i < 4; i++)
    {

        if (reader.hasNextInt()) {
            pid[i] = reader.nextInt();
            arrivaltime[i] = reader.nextInt();
            burstTime[i] = reader.nextInt();
        }
    }

    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM