1

I have an input like

...
...
..# 

if read in c++ it would be like:

int main() {
    char c;

    int n = 9;

    while(n--) {
       cin >> c;
    }
  return 0;
}

but in java I have tried doing:

public static void main(String args[]) {

    Scanner s =  new Scanner(System.in);
    int n = 9;
    char c;
    while(n--) {

        c = s.next().chartAt(0);

    }

}

it skips dots, I mean it only reads the first dot of each line.

There is not space between each dot.

MarioK17
  • 63
  • 6
  • 1
    Actually that C++ code would not read all the data in. You forgot the newlines. Also, I suggest you go back and read the Javadoc for `Scanner#next()`. – Jim Garrison Nov 23 '16 at 06:15
  • 1
    Read the entire line using `readLine()` and then get an array of chars by calling `toCharArray()` – TheLostMind Nov 23 '16 at 06:15
  • 1
    1st Google result for `java Scanner`: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html *A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.* Why not use System.in.read – TungstenX Nov 23 '16 at 06:18
  • See: https://stackoverflow.com/questions/15446689/what-is-the-use-of-system-in-read Is this what you want to do? – TungstenX Nov 23 '16 at 06:19
  • When I use read() I get Exception in thread "main" java.lang.NumberFormatException: For input string: "..#" because its counting the \n – MarioK17 Nov 23 '16 at 06:26

1 Answers1

0

When I was learning Java a long time ago, I always used this method to read a single character:

char c = s.findWithinHorizon(".", 0).charAt(0);

where s is the scanner.

After some testing, I found that this doesn't read new line characters! So this code works!

String input = "...\n...\n..#";
Scanner s = new Scanner(input);
for (int i = 0 ; i < 9 ; i++) {
    char c = s.findWithinHorizon(".", 0).charAt(0);
    // do whatever you want with c here
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313