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();
}

Dani AI

Generated

For the simple file shown (two integers per line: "1 2", "3 4", "5 6") there are two clean ways to meet the three goals you listed: (a) read the first int, (b) read the second int, and (c) skip the first line and load the remaining lines into a 2D array. is correct that a token reader returns values in sequence; the important nuance is whether you care about line boundaries. The OP ’s loop using Scanner.nextInt() will read tokens sequentially but won’t preserve row structure unless you explicitly group tokens into pairs.

A robust, easy-to-read approach is to treat the file as lines, parse the first line to extract the first and second integers, then parse the remaining lines into rows. That avoids mixing Scanner token methods and line methods (mixing them can lead to subtle nextLine() behavior). If the row/column counts are unknown, build rows into a List<int[]> and convert to int[][] when ready.

Example using java.nio.file (Java 8+):

List<String> lines = Files.readAllLines(Paths.get(fName));
if (lines.isEmpty()) throw new IllegalArgumentException("empty file");
String[] firstTokens = lines.get(0).trim().split("\\s+");
int first = Integer.parseInt(firstTokens[0]);
int second = Integer.parseInt(firstTokens[1]);

List<int[]> rows = new ArrayList<>();
for (int i = 1; i < lines.size(); i++) {
    String[] toks = lines.get(i).trim().split("\\s+");
    if (toks.length < 2) continue; // skip or handle malformed lines
    rows.add(new int[] { Integer.parseInt(toks[0]), Integer.parseInt(toks[1]) });
}
int[][] array = rows.toArray(new int[rows.size()][]);

Troubleshooting notes: validate token counts before parsing to avoid NumberFormatException, skip blank lines, and prefer streaming (Files.lines) for huge files. If you must use Scanner, either read the whole first line with nextLine() and parse it, or call nextInt twice then call nextLine() to advance past the rest of that line. This complements ’s token-point and ’s line-reading suggestion while keeping the 2D structure explicit.

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.