1

I have a file that contains numbers separated by a space, i can read in the file using scanner, and it displays just as the file shows it. How can i print the numbers vertically one by one?

try(Scanner reader = new Scanner(file)){
            while(reader.hasNextLine()){
                String line = reader.nextLine();
                System.out.println(line);
            }
user3803668
  • 25
  • 1
  • 6
  • current output 1 3 4 5 6 , desired output its the same but vertically. and adding an extra space between 1 and 3 – user3803668 May 02 '17 at 17:05

4 Answers4

1

You can use the operation split() on strings:
How to split a string in Java

String s = 1 2 3 4;
String[] result = s.split(" "); // this will split on space

Afterwards you can simply go through the array with a for-loop and print each value:

for(String str : result) {
    System.out.println(str);
}

Tipp: You can even limit the size of your array: string.split(" ", maxArraySize); will give you a String[] of length maxArraySize or shorter.

Community
  • 1
  • 1
goerlibe
  • 120
  • 1
  • 12
1

You need to split the resulting string from reader.nextLine() into an array.

try(Scanner reader = new Scanner(file)){
        while(reader.hasNextLine()){
            String line = reader.nextLine();
            //split line into an array, delimited by spaces
            String[] lines = line.split(" ");
            //loop through the resulting array
            for (int i = 0 ; i < lines.length; i++){
                //print each number on a single line
                System.out.println(lines[i]);
            }
        }
1

Split the line into a String[] by spaces and then iterate over the array printing each item on a new line.

String[] lines = line.split(" ");
for (String item : lines) {
    System.out.println(item);
}
Ishnark
  • 661
  • 6
  • 14
1

you'll need to split the String by the delimiter " " then simply iterate over those elements.

String line = reader.nextLine();
Arrays.stream(line.split(" ")).forEach(System.out::println);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126