user3266210
user3266210

Reputation: 299

skip first number, reading int from file java

Trying to read int from file. My problem is that my code read all the integers in the first line, but on the succeeding line it skips the first number. To illustrate my file has these numbers: 1, 4, 6, 7, 8, 11, 9, 1, 4, 6, 7, 8, 11, 12, 2, 4, 6, 7, 11, 12, 0,

but when i use the code below it only prints 1 4 6 7 8 11 9 then 4 6 7 8 11 12 then 2... it skips the first no.

Scanner file = null;
    ArrayList<Integer> listtwo = new ArrayList<>();
    try {
        file = new Scanner(new File(filename+".txt")).useDelimiter(",| ");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    while(file.hasNext()){
        if (file.hasNextInt()){ 
            listtwo.add(file.nextInt());
        }
        file.next();
    }
    for (Integer i: listtwo) System.out.println(i);

Upvotes: 0

Views: 1631

Answers (3)

fmi11
fmi11

Reputation: 85

You need to change

while(file.hasNext()){
        if (file.hasNextInt()){ 
            listtwo.add(file.nextInt());
        }
        file.next();
    }

to EDIT

int i = 0;
while(file.hasNextInt()){
   listtwo[i++] = file.nextInt();
}

In your code, it is first searching for the next "word" in the text file. The "if" statement then tells it to find the next int after that first "word", thus it skips the first number of the line.

Upvotes: 1

saravanakumar
saravanakumar

Reputation: 1777

Use like this file.next(); will run twise if you have file.hasNextInt() is true to avoid that use else case.

     while(file.hasNext()){
    if (file.hasNextInt()){ 
        listtwo.add(file.nextInt());
    }else{
       file.next();
    }
}

Upvotes: 0

PM 77-1
PM 77-1

Reputation: 13334

The problem is your

file.next();

Remove it.

Upvotes: 2

Related Questions