简体   繁体   中英

Java: taking char input from array results in infinite loop

This is the link the problem that I am trying to solve: https://dmoj.ca/problem/dmopc14c1p5

Here is the code that I have written for taking in input.

public static void main(String[] args) 
    {
        Scanner kbd = new Scanner(System.in);

        int y = kbd.nextInt(); //number of rows
        int x = kbd.nextInt(); //number of columns
        int initX = kbd.nextInt(); //initial starting position
        int initY = kbd.nextInt();
        int endX = kbd.nextInt(); //ending position (main office)
        int endY = kbd.nextInt();

        char [] [] maze = new char [y][x];

        for (int i = 0; i < y; i++)
        {
            for (int j = 0; j < x; j++)
            {
                maze[i][j] = kbd.next().charAt(0);
            }
        }

        //For checking
        for (int i = 0; i < y; i++)
        {
            for (int j = 0; j < x; j++)
            {
                System.out.print(maze[i][j]);
            }
            System.out.println();
        }


    }

However, I don't know how to properly take in the char input in the for loop. I used the scanner.next().charAt(0) method I found with this link ( How to take input for 'char' array in Java? ), but it results in an infinite loop that does not end no matter how many characters I input.

What am I doing wrong?

Update:

This is the input that I will be receiving (There are no white spaces between characters):

OOXOO
OXOXO
OOOXX
XOXOX
OOOOO

How should I modify my code to make reading this input possible?

Your code works properly. Just remembers that you need to type atleast x*y (your variable name) times of char.

EDIT: I just saw your update. We need to think about it a little bit.

.charAt(0)

Only takes the first character of a string and return it. If you want to take "ooxoo" and turn it into ['o','o','x','o','o'], you can use the toCharArray method on strings. However if you do this, your for loop will loop longer than needed. If you know your sets of input, you can only loop through n numbers of strings and accept them and convert them into array. Let me know if you want me to go more in details.

The java.util.Scanner.next() method finds and returns the next complete token from this scanner.

Every time you call kbd.next().charAt(0), you call next() and get a complete token. The tokens, by default, are separated by whitespace.

You also need to hit ENTER before System.in makes an data available.

So, enter your characters separated by spaces and end the input with a carriage return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM