0

I'm trying to read this input from the command line

1 2 3
4 5 6
7 8 9

But since it doesn't have an EOF the program throws a runtime error. I'm reading it in the following way inside a loop:

String holder = scanner.nextLine();

Any ideas of what I am missing here?

This is the code I'm using

package com.company;
public class Main {

public static void main(String[] args) throws IOException {
    Scanner scanner = new Scanner(System.in);
    int numCases = scanner.nextInt();
    scanner.nextLine();
    for(int i = 0; i < numCases; i++) {
        int matrixSize = scanner.nextInt();
        String ar = scanner.nextLine();
        int matrix[][] = new int[matrixSize][matrixSize];
        String rowNumbers[];
        for(int row = 0; row < matrixSize; row++) {
            String holder = scanner.nextLine();
            rowNumbers = holder.split( " ");
            for(int col = 0; col < matrixSize; col++) {
                matrix[row][col] = Integer.parseInt(rowNumbers[col]);
            }
        }

        int trace = calculateMatrixTrace(matrixSize, matrix);
        int repeatedInRows = countRepeatedInRows(matrixSize, matrix);
        int repeatedInCols = countRepeatedInCols(matrixSize, matrix);

        System.out.println("Case #" + (i + 1) + ":" + " " + trace + " " + repeatedInRows + " " + repeatedInCols);
    }
}

static int calculateMatrixTrace(int matrixSize, int matrix[][]) {
    int matrixTrace = 0;
    for(int i = 0; i < matrixSize; i++) {
        matrixTrace += matrix[i][i];

    }

    return matrixTrace;
}

static int countRepeatedInCols(int matrixSize, int matrix[][]) {
    int repeatedInCols = 0;
    List<Integer> numbersInCols = new ArrayList<>();
    for(int col = 0; col < matrixSize; col++) {
        for(int row = 0; row < matrixSize; row++) {
            int currentNumber = matrix[row][col];
            if (row != 0 && numbersInCols.contains(currentNumber))  {
                repeatedInCols += 1;
                break;
            }
            numbersInCols.add(matrix[row][col]);
        }
        numbersInCols.clear();
    }

    return repeatedInCols;
}

static int countRepeatedInRows(int matrixSize, int matrix[][]) {
    int repeatedInRows = 0;
    List<Integer> numbersInRows = new ArrayList<>();
    for(int row = 0; row < matrixSize; row++) {
        for(int col = 0; col < matrixSize; col++) {
            int currentNumber = matrix[row][col];
            if (col != 0 && numbersInRows.contains(currentNumber))  {
                repeatedInRows += 1;
                break;
            }
            numbersInRows.add(matrix[row][col]);
        }
        numbersInRows.clear();
    }
    return repeatedInRows;
}

}

ericgramirez
  • 153
  • 1
  • 9

2 Answers2

0

Try something like this:

// enter number of lines
int end = scanner.nextInt();
scanner.nextLine(); // clear lingering line delimiter.
for (int i = 0 i < end; i++) {
   String line = scanner.nextLine();
    // rest of your code here.
}

Another way is to enter a terminating token like "quit".

for (;;) {
   String line = scanner.nextLine();
   if (line.trim().equalsIgnoreCase("quit") {
      break;
    }
    // rest of your code here.
}

It is always useful to print out input prompts like so:

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter # cases: ");
        int numCases = scanner.nextInt();
        scanner.nextLine();
        for(int i = 0; i < numCases; i++) {
            System.out.print("Enter mat dimension: " );
            int matrixSize = scanner.nextInt();
            String ar = scanner.nextLine(); 
            // rest of code omitted
WJS
  • 22,083
  • 3
  • 14
  • 32
  • I'm not able to read the last line with scanner.nextLine(). That's the thing. – ericgramirez Apr 04 '20 at 18:17
  • I don't understand. Can you give an example. Both of the above read in all lines required. – WJS Apr 04 '20 at 18:19
  • The first example is the same thing I'm doing, but since it doesn't have EOF I'm unable to read the line. I can read the first two lines. – ericgramirez Apr 04 '20 at 18:26
  • Did you see the part about clearing the lingering newline. That is still there after you enter a value so you need to get rid of it before reading in your data. – WJS Apr 04 '20 at 18:27
  • Yes, I'm also doing that. I just wrote the code that's trying to read the 3 lines, my bad. – ericgramirez Apr 04 '20 at 18:31
  • Edit your answer and post your code. And what system are you using and/or IDE? – WJS Apr 04 '20 at 18:37
  • I'm using Arch Linux and IntelliJ IDEA – ericgramirez Apr 04 '20 at 18:40
  • It works fine for me. You realize you are prompting for the matrix size for each case? So you need to enter that each time and then enter your values. – WJS Apr 04 '20 at 19:01
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210948/discussion-between-wjs-and-ericgramirez). – WJS Apr 04 '20 at 19:06
  • Did you see my last comment. Your program works fine. Just remember that after each line you must hit the enter key. – WJS Apr 04 '20 at 20:12
0

Use nextLine() instead of next(), nextInt() etc. Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.

Do it as follows:

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

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the no. of cases: ");
        int numCases = Integer.parseInt(scanner.nextLine());
        for (int i = 0; i < numCases; i++) {
            System.out.print("Enter the size of matrix: ");
            int matrixSize = Integer.parseInt(scanner.nextLine());
            int matrix[][] = new int[matrixSize][matrixSize];
            System.out.println("Enter the matrix: ");
            String rowNumbers[];
            for (int row = 0; row < matrixSize; row++) {
                String holder = scanner.nextLine();
                rowNumbers = holder.split(" ");
                for (int col = 0; col < matrixSize; col++) {
                    matrix[row][col] = Integer.parseInt(rowNumbers[col]);
                }
            }
            System.out.println("matrix[][]: " + Arrays.deepToString(matrix));
        }
    }
}

A sample run:

Enter the no. of cases: 1
Enter the size of matrix: 3
Enter the matrix: 
1 2 3
4 5 6
7 8 9
matrix[][]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Feel free to comment in case of any doubt/issue.

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
  • After changing the code I'm getting: Exception in thread "main" java.lang.NumberFormatException – ericgramirez Apr 04 '20 at 19:26
  • `I'm getting: Exception` - You mean when you are including this solution with the rest of your program? If yes, can you please simply copy and run my program without any change (i.e. without combining it with the rest of your code)? Once you confirm it, I will look into the rest of your code. I'm waiting for your response. – Arvind Kumar Avinash Apr 04 '20 at 19:29
  • Sorry, I forgot to delete one of the scanner.readLine() I've written before. It is working, but I can't still read the last line. I don't know If I've explained myself correctly :( – ericgramirez Apr 04 '20 at 19:33
  • *I can't still read the last line* - Are you not getting the output `matrix[][]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]` when you run my code? How are you entering the data? There are two ways to enter the data - either you enter all the three lines (i.e. 1 to 9) together or you enter the lines one by one (i.e. 1 2 3 Enter then 4 5 6 Enter then 7 8 9 Enter). This solution works for both these cases. Are you entering the data in some other way? If yes, let me know so that I can suggest you the solution accordingly. – Arvind Kumar Avinash Apr 04 '20 at 19:41
  • I'm entering all the three lines, but I don't press enter o any other keyword after that. So there's no EOF. As a result it doesn't read the last line. – ericgramirez Apr 04 '20 at 19:44
  • `Scanner` for `System.in` doesn't understand `EOF`. All it understands is a line separator which you input using `Enter` key. Is there any reason why you do not want to press `Enter`? – Arvind Kumar Avinash Apr 04 '20 at 19:48
  • I'm actually submitting the code to an online judge and it's giving me Runtime Error. I don't know why, it doesn't say why. It's occured to me maybe it's because the program gets hung somewhere. – ericgramirez Apr 04 '20 at 19:53
  • Thank for your help Arvind. I was trying to submit that code to a code judge, it wasn't working because I didn't earse the "import", I forgot to mention that detail in my explanation. – ericgramirez May 19 '20 at 10:28