Search code examples
javaarraysjava.util.scanner

Java: Read a word until space and store in array


I'm trying to write a program that can read two words separated by a space that is been entered by the user and store it in an array. So far, I only did this:

String[] wordsArray = new String[2];
System.out.print("Next, enter two words:");
wordsArray[0] = scannerlmao.nextLine();
wordsArray[1] = scannerlmao.nextLine();
System.out.println("You entered \"" + wordsArray[0] + "\" and \"" + wordsArray[1] + "\""); 

Input:
mike alpha

Expected output:
You entered "mike" and "alpha"

Issue:
You entered "" and "mike alpha"

Right now it only stored it on the second index of the array. I looked it up online but either for characters or numbers only showed up. Can we do it with this method or do we need a completely different way?


Solution

  • you have just to use .next() instead of .nextLine()

    next() : read the next word, but nextLine(): read all the words entered in the same line.

    class Main {
        public static void main(String[] args) {
            Scanner scannerlmao = new Scanner(System.in);
            String[] wordsArray = new String[2];
            System.out.print("Next, enter two words:");
            wordsArray[0] = scannerlmao.next();
            wordsArray[1] = scannerlmao.next();
            System.out.println("You entered \"" + wordsArray[0] + "\" and \"" + wordsArray[1] + "\"");
        }
    }