Print integers to a new line until a certain point

moo cow :

Let's say I have a text file with this:

2 4 6 7 -999
9 9 9 9 -999

When I run the program, I should print out everything except the "-999" on each line. What I should get is:

 2 4 6 7 
 9 9 9 9 

This is what I've tried:

public class Prac {
public static void main(String[] args) throws FileNotFoundException {

    Scanner reader = new Scanner(new File("test.txt"));
    while(reader.hasNextLine() && reader.nextInt() != -999) {
        int nextInt = reader.nextInt();
        System.out.print(nextInt + " ");
    }

}

}

I've tried using while/for loops but don't seem to get this to work and the numbers are not on different lines. I don't get why the condition does not work when I run the code and each line is not separated while printing. I've been trying to find a solution for a while and decided to ask here. It's probably an easy question but I haven't coded in a while, so let me know. Thanks in advance.

y.luis :

The reader.nextInt() in the while will consume the next int, so you will be always skipping an integer. So I would suggest:

    public static void main(String[] args) throws FileNotFoundException {
        Scanner reader = new Scanner(new File("test.txt"));
        while (reader.hasNextLine()) {
            int nextInt = reader.nextInt();
            if (nextInt != -999)
                System.out.print(nextInt + " ");
            else
                System.out.println();
        }
    }

Update: In case you want to calculate the average for each line, as requested in your comment, you could store each value to make the calculations (see here other ways). The code below will do that and print the average at the end of the line:

    public static void main(String[] args) throws FileNotFoundException {
        Scanner reader = new Scanner(new File("test.txt"));
        List<Integer> values = new ArrayList<>();
        while (reader.hasNextLine()) {
            int nextInt = reader.nextInt();
            if (nextInt != -999) {
                System.out.print(nextInt + " ");
                values.add(nextInt);
            } else {
                int sum = 0;
                for (int value : values) {
                    sum += value;
                }
                System.out.println((float) sum / values.size());
                values.clear();
            }
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112562&siteId=1