0

The file looks like this

the code I am currently trying:

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

    String content = new Scanner(new File("test/input_file.txt")).useDelimiter("\\z").next();
    System.out.println(content);
    String room = content.substring(0,3);
    System.out.println("room size:");
    System.out.println(room);

}

I want to read each data line of data, and be able to use them, eg. the first line is 10, I want to be able to create a variable to store it, but if the first line is 9, my code would not be working since I am using the substring.

So, How can I read the file, and put the data in multiple variables? such as I want to read the first line and store it in a variable named room, read the second line, and store it as firstcoordinate_x, and firstcoordinate_y.

4
  • 1
    And what is your question? Commented Dec 3, 2016 at 22:40
  • Why do you need to take a substring if the line is just one thing anyway? Commented Dec 3, 2016 at 22:41
  • if I don't use substring, how can I get the data in the first line? Commented Dec 3, 2016 at 22:46
  • Welcome to Stack Overflow! It looks like you are asking for homework help. While we have no issues with that per se, please observe these dos and don'ts, and edit your question accordingly. Commented Dec 3, 2016 at 22:51

1 Answer 1

1

Here's an example for the first two lines :

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


public class ParseFile
{
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("input_file.txt"));

        int roomSize = Integer.valueOf(scanner.nextLine());
        System.out.println("room size:");
        System.out.println(roomSize);

        String first_xy = scanner.nextLine();
        String[] xy = first_xy.replaceAll("\\(|\\)", "").split(",");
        int x1 = Integer.valueOf(xy[0]);
        int y1 = Integer.valueOf(xy[1]);

        System.out.println("X1:");
        System.out.println(x1);
        System.out.println("Y1:");
        System.out.println(y1);

        scanner.close();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.