Trevor Holland
Trevor Holland

Reputation: 3

Formatting an output from a file

I want to format an output so that it after printing a set of data, to set it so the line returns after a certain amount of data entries.
The Data I want to have entered and appear as is as follows:

10 5 2 0 0
10 5 0 0 0
10 8 3 40 25
8 20 0 30 60
9 6 4 20 33
8 4 1 30 20
4 8 1 20 30
6 6 1 20 20
7 0 6 30 25
9 2 2 25 10

(The file location given in the code below houses a text file that has the set of numbers above inside)

The program I have so far is as follows:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class SoccerRunner {

public static void main(String[] args) throws IOException {

    //Path to file location
    String pathToFile = "C:\\Users\\Trevor\\Downloads";

    //Data file name & reader
    File inFile = new File(pathToFile, "SoccerData.txt");
    Scanner inData= new Scanner(inFile);


    int someData;

    while (inData.hasNext())
    {
        someData = inData.nextInt();
        System.out.print(someData + "\t");
    }

}

}

I would like to know if I'm missing something and if so what I am missing. Thank you for your help!

Upvotes: 0

Views: 55

Answers (2)

Kunjan Thadani
Kunjan Thadani

Reputation: 1670

You can use a counter like this:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class SoccerRunner {

public static void main(String[] args) throws IOException {

//Path to file location
String pathToFile = "G:\\";

//Data file name & reader
File inFile = new File(pathToFile, "sample.txt");
Scanner inData= new Scanner(inFile);


int someData;
int count=1;
while (inData.hasNext())
{

    someData = inData.nextInt();

    System.out.print(someData + "\t");
    count++;
    if(count==5){
        System.out.print("\n");
        count=1;
    }

}

}

}

Upvotes: 2

Peter
Peter

Reputation: 5798

if you want a new line then you have to write a new line

add a System.getProperty("line.separator") after each line

or simply using System.out.println() would work to to go to next line

Upvotes: 0

Related Questions