0

I started doing the CodeAbbey problems last night, they mentioned using stdIn since some the input data is long so copy/paste is much easier than by hand. I had never used the Scanner before so it looked easy enough. I got it working for single line inputs then I got a problem where the input was:

867955 303061
977729 180367
844485 843725
393481 604154
399571 278744
723807 596408
142116 475355 

I assumed that nextLine would read each couple, xxxx yyyyy. I put the code in a while loop based on if nextLine is not empty. It runs, but I get weird output, and only after I hit return a few times.

package com.secryption;

import java.util.Scanner;


public class Main {

    public static void main(String[] args) {

        System.out.println("Input: ");
        Scanner scanner = new Scanner(System.in);
        String input = "";


        while(!(scanner.nextLine().isEmpty())) {
            input = input + scanner.nextLine();
        }
        String[] resultSet = input.split("\\s+");

        for(String s : resultSet) {
            System.out.println(s);
        }


    }

}

I thought I might need something after adding scanner.nextLine() to input. I tried a space and that didn't help. I tried a newline and that didn't make it better.

This "should" put all the numbers in a single array, nothing special. What am I missing with scanner?

EDIT: Ok so @Luiggi Mendoza is right. I found this How to terminate Scanner when input is complete? post. So basically it it working, I just expected it to do something.

Community
  • 1
  • 1
TheEditor
  • 486
  • 1
  • 4
  • 18

2 Answers2

1

The problem is here:

while(!(scanner.nextLine().isEmpty())) {
    input = input + scanner.nextLine();
}

Scanner#nextLine reads the line and will continue reading. You're reading two lines and not storing the result of the first line read, just reading and storing the results of the second.

Just change the code above to:

StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()) {
    sb.append(scanner.nextLine()).append(" ");
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • That outputs the right data but only after I stop it. Doesn't that mean it's still just sitting there in the while loop? – TheEditor Aug 28 '15 at 23:26
0

hasNext() is an end of file indicator that terminates by combining keys control d on Mac ox and control z on windows pressing enter won't send the right message to JVM

Monday A Victor
  • 441
  • 5
  • 16