Multiple String Input In Java Using Scanner [With Coding Example]

Introduction

In java.util package, the scanner is one of the classes that help in collecting multiple inputs of the primitive types such as double, integer, strings, etc. Though it is not an efficient way of reading inputs in a Java program where time acts as a constraint, it is undoubtedly one of the easiest ways to collect multiple inputs from the user. In this blog, you will learn how to collect multiple string input from the user in a Java program using the scanner class.

Methods for Taking Multiple Inputs Using Scanner

You must import java.util package in a program before using the Scanner class. The following table lists the methods used to take multiple inputs of different types from the user in a Java program.

Method Inputs
nextInt() Integer
nextFloat() Float
nextDouble() Double
nextLong() Long
nextShort() Short
next() Single-word
nextLine() Line of Strings
nextBoolean() Boolean

Using Java nextLine() Method

The java.util.Scanner.nextLine() method returns the line that was skipped by advancing the scanner past the current line. If a line separator is given at the end of the current line, this method excludes it and returns the string’s rest from the current line. The scanner is set at the next line beginning and reads the entire string, including the words’ white spaces.

The syntax for nextLine() method is as follows:

Public String nextLine()

This method throws the following two exceptions:

  • NoSuchElementException – If the string is empty or no line is found.
  • IllegalStateException – If the scanner is closed.

Example

The following example demonstrates how java.util.Scanner.nextLine() method collects multiple inputs from the user.

import java.util.Scanner; 

public class SacnnerDemoMultipleString 

public static void main(String[] args)  

Scanner demo = new Scanner(System.in); 

System.out.print(“Please enter multiple inputs you want to print: “);  

//takes an integer input    

String[] string = new String [demo.nextInt()]; 

//consuming the <enter> from input above 

demo.nextLine();  

for (int i = 0; i < string.length; i++)  

string[i] = demo.nextLine(); 

System.out.println(“\nYou have entered the following input: “); 

//for-each loop to print the string 

for(String str: string)  

System.out.println(str);

// close the scanner

scanner.close();

The above program will print the following output

Please enter multiple inputs you want to print:  7

Misha

Harry

Robert

Harvey

Jill

Rachel

Jennifer

You have entered the following input:

Misha

Harry

Robert

Harvey

Jill

Rachel

Jennifer

Using Java nextInt() Method

The java.util.Scanner.nextInt() method scans the input provided by the user as an integer. If an integer is found, then the scanner advances past the matched input.

The syntax for nextInt() method is as follows:

Public int nextInt()

This method throws the following three exceptions:

  • InputMismatchException – If the next token does not match the integer regular expression or if the next token is out of the range.
  • NoSuchElementException – If the input is exhausted.
  • IllegalStateException – If the scanner is closed.

Example

The following example demonstrates how java.util.Scanner.nextInt() method collects multiple inputs from the user.

// Java program to scan integer using Scanner

// class and print their mean.

import java.util.Scanner;

public class ScannerDemoInteger

{

public static void main(String[] args)

{

 Scanner demo = new Scanner(System.in);

// Initialize sum and count of input elements

 int sum = 0, count = 0; 

// Check if an integer value is present

while (demo.hasNextInt())

 {

// Scan an integer value

int num = demo.nextInt();

sum += num;

count++;

 }

int mean = sum / count;

System.out.println(“Mean: ” + mean);

}

}

The above program is fed with the following input:

101

223

238

892

99

500

728

The above program will print the following output:

Mean: 397

Also Read:  Java MVC Project 

Using Java nextDouble() Method

The java.util.Scanner.nextDouble() method scans the input provided by the user as a double. If a float regular expression is found, then the scanner advances past the matched input.

The syntax for nextInt() method is as follows:

public double nextDouble()

This method throws the following three exceptions:

  • InputMismatchException – If the next token does not match the float regular expression or if the next token is out of the range.
  • NoSuchElementException – If the input is exhausted.
  • IllegalStateException – If the scanner is closed.

Example

The example demonstrates how java.util.Scanner.nextDouble() method collects multiple inputs from the user.

// Java program to scan float using Scanner

import java.util.Scanner;

public class ScannerDoubleRegularExpression {

public static void main(String[] args) {

String new = “Good Morning! 3 + 3.0 = 6 true”;

// write a new scanner object with the specified String Object

Scanner demo = new Scanner(s);

 // use US locale to be able to identify doubles in the string

demo.useLocale(Locale.US);

// search the next double token and print it

while (demo.hasNext()) {

// if the next is a double, print found and the float regular expression

if (demo.hasNextDouble()) {

 System.out.println(“Found :” + demo.nextDouble());

 }

// if a double regular expression is not found, print “Not Found” and the token

System.out.println(“Not Found :” + demo.next());

 }

// close the scanner

scanner.close();

}

}

The above program will result in the following output:

Not Found: Good

Not Found: Morning!

Found: 3.0

Not Found: +

Found: 3.0

Not Found: =

Found: 6.0

Not Found: true

Conclusion

For example, the codes given in this blog are the purpose and can be modified as per an individual’s needs. If you’re interested to learn more about Java & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
LEARN MORE

Leave a comment

Your email address will not be published.

×