简体   繁体   中英

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]. 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. 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.

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();
        }
    }

    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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