Search code examples
javaarrayseclipsestdin

StdIn reads line break as char


I am trying to get a user input (StdIn from the Princeton Java course) and save it into a char[][]. The input comes in this format:

0.........
1.........
2.........
3.........
4.........
..........
.........3
.........2
.........1
.........0

When I compile and run my code using javac in cmd, it works and prints the array formatted correcly, however it turns into a mess in Eclipse. This is the code I am using:

    int row = 10;
    int col = 10;
      char[][] input = new char[row][col];
      for(int i = 0; i<10; i++) {
          for (int j = 0; j<10; j++) {
              input[i][j] = StdIn.readChar();
          }
      }
      for (int i = 0; i<10; i++) {
          for (int j = 0; j<10; j++) {
              System.out.print(input[i][j]);
          }
          System.out.println();
      }

It is supposed to print the Array in the same format as the input.

EDIT: I found the problem: StdIn.readChar() also reads the line break as a single char and fills the array with it. Is there an elegant way to prevent this?


Solution

  • You should check for Carriage Return (CR) or Line Feed (LF) characters, in Windows hosts line breaks are made with CR+LF, on Linux only with LF. Using System.getProperties("line.separator") or System.lineSeparator() you obtain a string with the character(s) used to start a new line depending on your OS.

    But you can simplify this process using java.util.Scanner or java.io.BufferedReader

    Example with Scanner:

    int row = 10;
    int col = 10;
    char[][] input = new char[row][col];
    Scanner in = new Scanner(System.in);
    for(int i=0; i < row; i++){
        input[i] = in.nextLine().toCharArray();
    }
    

    Example with BufferedReader (you also need to import java.io.InputStreamReader and the method used could thrown IOException, so I think it's simpler to use Scanner, but, if you want..)

    int row = 10;
    int col = 10;
    char[][] input = new char[row][col];
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    for(int i=0; i < row; i++){
        input[i] = reader.readLine().toCharArray();
    }
    

    The two implementations are very similar, you could choose the one you prefer, I think it's not convenient to check if each character is different from CR ("\r") and/or from LF ("\n")