How to Take Multiple String Input in Java Using Scanner
In Java, Scanner is a class that provides methods for input of different primitive types. It is defined in java.util package. In this section, we will learn how to take multiple string input in Java using Scanner class.
We must import the package before using the Scanner class. For example, if want to take input a string or multiple string, we use naxtLine() method. It is only a way to take multiple string input in Java using the nextLine() method of the Scanner class.
Java nextLine() Method
The nextLine() method moves the scanner down after returning the current line. It reads String input including the space between the words. It does not accept any parameter. It returns a String (line) of that was skipped.
Syntax:
The method throws the NoSuchElementException if it does not find a line and throws IllegalStateException if the Scanner is closed.
Let’s create a program that takes multiple String input.
In the following example, we have created an instance of the Scanner class. After that, we have invoked the nextLine() method that takes the string as input. At last, with the help of a for-each loop, we have printed all the strings that we have entered.
MultipleStringInputExample1.java
Output:
Please enter the number of strings you want to enter: 5 Robert Harry Charlie Thomas David You have entered: Robert Harry Charlie Thomas David
Let’s see another example.
In the following example, we have used the Scanner class. But did not use the nextLine() method. Instead of it, we have used forEachRemaining() method.
It is a Java Interface Spliterator that is used to perform the specified action for each element sequentially in the current thread. It executes until all elements have been processed or the action throws an exception. It does not return anything.
Syntax:
It throws NullPointerException if the action is null.
MultipleStringInputExample2.java
Output:
Enter the elements: Java Java Python Python Pascal Pascal C++ C++
Using Lambda Expression
We can also write the above program in the following manner by using the lambda expression.
MultipleStringInputExample3.java
Output:
Canada Canada America America Russia Russia France France
The following example also takes the multiple String input. But in this example, we have used another method hasNextLine(). The method returns true if there is another line of input of this scanner. The while loop execute until the method hasNextLine() returns false.
MultipleStringInputExample4.java
Output:
Apple Apple Grapes Grapes Watermelon Watermelon
In the following example, we have used a for loop that executes up to n times. Inside the loop, we have called the nextLine() method that takes the String input.
MultipleStringInputExample5.java
Output:
Enter the elements: Data Structure Data Structure Web Services Web Services Web Designing Web Designing