How to Read Multiple Strings in a Line in Java
Multiple Cord Input In Java Using Scanner [With Coding Example]
Feb 5, 2021
Introduction
In java.util packet, 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 non an efficient manner of reading inputs in a Java program where time acts as a constraint, it is undoubtedly 1 of the easiest ways to collect multiple inputs from the user. In this blog, you will acquire how to collect multiple string input from the user in a Coffee 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 post-obit table lists the methods used to take multiple inputs of dissimilar types from the user in a Coffee program.
Method | Inputs |
nextInt() | Integer |
nextFloat() | Bladder |
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 past advancing the scanner by the current line. If a line separator is given at the end of the electric current line, this method excludes it and returns the string'south rest from the electric current line. The scanner is set at the next line offset and reads the entire cord, including the words' white spaces.
The syntax for nextLine() method is as follows:
Public String nextLine()
This method throws the post-obit two exceptions:
- NoSuchElementException – If the string is empty or no line is institute.
- IllegalStateException – If the scanner is closed.
Instance
The post-obit case demonstrates how coffee.util.Scanner.nextLine() method collects multiple inputs from the user.
public class SacnnerDemoMultipleString
{
public static void main(String[] args)
{
Scanner demo = new Scanner(System.in);
Organisation.out.print("Please enter multiple inputs you want to print: ");
//takes an integer input
Cord[] string = new Cord [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)
{
Organization.out.println(str);
// shut the scanner
scanner.shut();
}
}
}
The above programme will print the following output
Misha
Harry
Robert
Harvey
Jill
Rachel
Jennifer
You lot accept entered the post-obit 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 equally an integer. If an integer is institute, then the scanner advances past the matched input.
The syntax for nextInt() method is every bit follows:
Public int nextInt()
This method throws the following 3 exceptions:
- InputMismatchException – If the next token does not friction match the integer regular expression or if the adjacent token is out of the range.
- NoSuchElementException – If the input is wearied.
- IllegalStateException – If the scanner is airtight.
Example
The post-obit example demonstrates how coffee.util.Scanner.nextInt() method collects multiple inputs from the user.
// class and print their mean.
import java.util.Scanner;
public form ScannerDemoInteger
{
public static void main(String[] args)
{
Scanner demo = new Scanner(Arrangement.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 hateful = sum / count;
Organisation.out.println("Mean: " + mean);
}
}
The to a higher place programme is fed with the post-obit input:
223
238
892
99
500
728
The above program volition impress the following output:
Also Read: Java MVC Projection
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 by the matched input.
The syntax for nextInt() method is as follows:
public double nextDouble()
This method throws the following 3 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 airtight.
Instance
The instance demonstrates how coffee.util.Scanner.nextDouble() method collects multiple inputs from the user.
import java.util.Scanner;
public grade ScannerDoubleRegularExpression {
public static void chief(String[] args) {
String new = "Skilful Morning time! 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 impress it
while (demo.hasNext()) {
// if the side by side is a double, print institute and the float regular expression
if (demo.hasNextDouble()) {
Arrangement.out.println("Institute :" + demo.nextDouble());
}
// if a double regular expression is not found, print "Not Found" and the token
Organization.out.println("Not Constitute :" + demo.next());
}
// close the scanner
scanner.close();
}
}
The above plan will consequence in the post-obit output:
Not Institute: Morning!
Institute: three.0
Not Constitute: +
Found: 3.0
Non Found: =
Found: 6.0
Non Plant: truthful
Acquire Software Development Courses online from the World'southward top Universities. Earn Executive PG Programs, Avant-garde Certificate Programs, or Masters Programs to fast-track your career.
Decision
For case, the codes given in this weblog are the purpose and tin be modified as per an private's needs. If you're interested to learn more about Java & full-stack software development, check out upGrad & IIIT-B'southward Executive PG Program in Total-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 easily-on capstone projects & job help with summit firms.
Set for a Career of the Future
Source: https://www.upgrad.com/blog/multiple-string-input-in-java-using-scanner/
0 Response to "How to Read Multiple Strings in a Line in Java"
Post a Comment