Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 19 February, 2024

29.89K+ views
6 min read

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. 

This article aims to share practical insights and methods for using the Scanner class to capture multiple inputs seamlessly. By exploring techniques such as the Java nextLine() method, as well as nextInt() and nextDouble() methods, I hope to equip you with the knowledge to implement these strategies effectively in your projects. As we dive into these methods, the goal is to provide a comprehensive guide that will improve your ability to develop dynamic Java applications through proficient input handling. 

Check out our free courses to get an edge over the competition.

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

Check out upGrad’s Java Bootcamp

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.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

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 

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

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

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

Mastering multiple string input in Java using a scanner is a fundamental skill for Java developers, enhancing the versatility and interactivity of Java applications. This article has demonstrated efficient methods to capture multiple inputs using the Scanner class, including the use of nextLine(), nextInt(), and nextDouble() methods. Each method serves a unique purpose, catering to different data types and ensuring that Java developers can handle user inputs with precision and ease. By integrating these techniques into Java programming, developers can build more dynamic, user-friendly applications. It is imperative for practitioners to understand these methods thoroughly to manage input in Java applications effectively. As we have seen, the Scanner class provides a straightforward and powerful toolset for dealing with multiple string inputs, showcasing the strength and flexibility of Java for handling diverse user input scenarios. 

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 Executive PG Program 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.

Frequently Asked Questions (FAQs)

1. What is Scanner class in Java?

The Scanner class lets you read values from the keyboard without using Java's console input. Java's console input is slow, and so is its redirection. Scanner is faster and more convenient, so Scanner should be used in place of Java's console input. Scanner uses Java's regular input stream, so it can be chained with other parsers. Scanner is also easier to use than Java's console input. Scanner has three main subclasses, namely, BufferedReader, InputStreamReader, and FileReader. The most general one is BufferedReader. BufferedReader can read anything that can be read by InputStreamReader, and it has one big advantage: buffer. The buffer can hold one line at a time. An input stream has no buffer at all: when you call next(), it returns the value. This means you have to collect the values before you can do anything with them. Scanner does it for you.

2. What is a string builder in Java?

A string builder is a new type of class to create a string. The string builder class is introduced in Java from 1.3 version. It allows you to create a string by concatenating a number of strings and will automatically resize itself as you add more strings to it. Compared to string concatenation, using string builder is faster and flexible, though it's less readable. StringBuilder objects are objects that are used to create String values. StringBuilder objects have a number of methods.

3. What is an InputStreamReader in Java?

InputStreamReader reads a stream of characters from an input stream and decodes them into a specified character encoding. It provides an easy way to convert character streams from one encoding to another. InputStreamReader reads bytes from the underlying stream and converts them into characters using the specified charset encoding. It is a class that is used to convert byte stream data into character stream data. Byte stream represent binary data and character stream represent text.

RELATED PROGRAMS