I have a file with ints like this.

1 2

3 4

5 6

How to read first int from file?

How to read second int from file?

How to skip first line and but rest in 2d array?

This is what I have so far. I am not sure how to read 2nd int from file and to put rest in 2d array.

Scanner f = new Scanner(new File(fName));

//read first number
int num1 = f.nextInt();

//skip first line and put rest in 2d array
while(f.hasNextInt()){
    a[i++] = f.nextInt();
}

Recommended Answers

All 2 Replies

After you read the first int, the next call will read the second number

int num1 = f.nextInt(); // reads 1nd num
int num2 = f.nextInt(); // reads 2nd num

similarly in the loop you can call nextInt twice to get the two numbers and put them into the 2D array

Just and example

public Account(String username) throws FileNotFoundException, IOException {
        this.username = username;

        File folder = new File("C:\\"+username);
        File file = new File(folder, username + ".txt");

        FileReader freader = new FileReader(file);
        try (BufferedReader breader = new BufferedReader(freader)) {
            String line;
            String[] parts;
            String key, value;
            while ((line = breader.readLine()) != null) {
                parts = line.split("=");
                key = parts[0].trim();
                value = parts[1].trim();
                switch (key) {
                    case "Name":
                        name = value;
                        break;
                    case "Password":
                        password = value;
                        break;
                    case "Security Code":
                        securityCode = value;
                        break;
                    case "Card ID":
                        cardID = value;
                        break;
                    case "Admin":
                        admin = Integer.parseInt(value);
                        break;
                    case "Bank Rob":
                        bankrob = Integer.parseInt(value);
                        break;
                    case "Credit":
                        credit = Integer.parseInt(value);
                        break;
                }
            }
        }
    }

Name = Stefan
Age = 20
etc..

commented: Does not answer the OP's question +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.