How to input string in java

Tutorial: Accepting String Input in Java

Some Java programs need input from the user. To accept input from the user, use the Scanner class. The Scanner class has methods that accept different types of input. This tutorial describes string input. First, import the Scanner class at the top of your program:

import java.util.Scanner; //NEW public class Example  public static void main(String[] args)  > > 
import java.util.Scanner; public class Example  public static void main(String[] args)  Scanner input = new Scanner(System.in); //NEW > > 

This Scanner object accepts input from System.in , or the console. The variable name input refers to the Scanner object. Now prompt the user to enter a string:

import java.util.Scanner; public class Example  public static void main(String[] args)  Scanner input = new Scanner(System.in); System.out.print("What's your name? "); //NEW > > 

Since System.out.print() does not output a newline character, the user will input the string on the same line as the question. Next, use the Scanner input variable to accept one string from the console:

import java.util.Scanner; public class Example  public static void main(String[] args)  Scanner input = new Scanner(System.in); System.out.print("What's your name? "); String s = input.next(); //NEW > > 

The next() method accepts the next string from the console. If the user enters multiple string values, separated by whitespace, the next() method captures the first string value only. Finally, output the string value that the user entered:

import java.util.Scanner; public class Example  public static void main(String[] args)  Scanner input = new Scanner(System.in); System.out.print("What's your name? "); String s = input.next(); System.out.println("Hello " + s); //NEW > > 
What's your name? Edwin Hello Edwin 
import java.util.Scanner; public class Example  public static void main(String[] args)  Scanner input = new Scanner(System.in); System.out.print("What are your first and last names? "); String first = input.next(); String last = input.next(); System.out.println("Hello " + first + " " + last); > > 

The first next() statement accepts the first input string. The second next() statement accepts the second input string. Here is a sample run of the program:

What are your first and last names? Edwin Torres Hello Edwin Torres 
import java.util.Scanner; public class Example  public static void main(String[] args)  Scanner input = new Scanner(System.in); System.out.print("What are the colors of the rainbow? "); String colors = input.nextLine(); System.out.println("The colors are: " + colors); > > 
What are the colors of the rainbow? red orange yellow green blue indigo violet The colors are: red orange yellow green blue indigo violet 

That’s it! The Scanner class is useful for accepting input from the user. This tutorial discusses string input and the different ways to accept string values from the user. Thanks for reading. 😃 Follow me on Twitter @realEdwinTorres for more programming tips and help.

Источник

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to take String input in Java:

  1. By Using Java Scanner class
  2. By Using Java BufferedReader class
  3. By Using the Command Line argument

By Using Java Scanner class

The Scanner class is defined in java.util package that is used to take input from the user. The Scanner class provides the following two methods to take input from the user.

Let’s discuss each of the mentioned methods to take input from the user.

1. Scanner.nextLine() Method

The nextLine() method reads the input till the line gets terminated and shifts the cursor to the next line. The syntax of the nextLine() method is:

The method does not accept any parameter. It returns the string that was skipped. If the method finds no line to read, the method throws the NoSuchElementException.

FileName: StringInputExample.java

// importing the Scanner class import java.util.Scanner; public class StringInputExample < // main method public static void main(String argvs[]) < // To hold the string input by the user String str; // creating an object of the Scanner class Scanner scnr = new Scanner(System.in); System.out.print("Enter a string: "); // invoking the method nextLine() // to take input from the user str = scnr.nextLine(); // for new line System.out.println(); // displaying the entered string System.out.print("The string entered by the user is: " + str ); >>

String Input in Java 1

Explanation: After displaying the message Enter a string, the cursor waits on the console for the user to enter string. The method nextLine() reads till the user hits enter and return the read stuff, which is captured by the variable str. The same read string is shown in the output. Note that hitting the enter button shows that the line has been terminated.

Scanner.next() Method

The next() method reads the input till the line gets terminated or white space is encountered. The main difference between the nextLine() and next() method is that the latter one terminates when white space is encountered, where the former one terminates only when enter is pressed. The syntax of the next() method is:

The read line is returned.

The method does not accept any parameter. It returns the string that was skipped. If the method finds no line to read, the method throws the NoSuchElementException.

FileName: StringInputExample1.java

// importing the Scanner class import java.util.Scanner; public class StringInputExample1 < // main method public static void main(String argvs[]) < // To hold the string input by the user String str; // Instantiating the Scanner class by creating its object Scanner scnnr = new Scanner(System.in); System.out.print("Enter a string: "); // invoking the method next() // to take input from the user str = scnnr.next(); // for new line System.out.println(); // displaying the entered string System.out.print("The string entered by the user is: " + str ); >>

String Input in Java 1

Explanation: The user enters My Name is Khan. However, after the word “My” white space is encountered. Hence, the rest three words are not read, and the same can be confirmed by observing the output.

By using Java BufferedReader Class

Java BufferedReader Class is used to read the stream of characters. The class accepts an object of the InputStreamReader class. So, it is necessary to create a constructor of the InputStreamReader class and pass its object to the BufferedReader class as a parameter. The BufferedReader class has the readLine() method to take input from a user. The readLine() method reads one line at a time.

It returns the line entered by the user. It does not include any line-termination characters, or null if the end of the stream has been reached.

Let’s observe the following program to understand how the BufferedReader class is used for taking input from the user.

FileName: StringInputExample2.java

// Import statements import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class StringInputExample2 < // main method public static void main(String argvs[]) throws IOException < String str; // Creating an object of the InputStreamReader class InputStreamReader inputStrObj = new InputStreamReader(System.in); // Creating an object of the BufferedReader class BufferedReader bufrObj = new BufferedReader(inputStrObj); System.out.print("Enter a string: "); // invoking the method readLine() // to take input from the user str = bufrObj.readLine(); // for new line System.out.println(); // displaying the entered string System.out.print("The string entered by the user is: " + str ); >>

String Input in Java 1

Explanation: In the constructor of the InputStreamReader class, System.in is passed. It is done because the input is being taken from the keyboard. With the help of InputStreamReader class, the BufferedReader class stores the input given by the user through keyboard.

By using the Command Line Argument

Command Line argument is present in the main method (String argvs[]). String argvs[] is a string array that accepts a line as an input. Let’s understand the usage of command-line argument with the help of the following Java program.

FileName: StringInputExample3.java

public class StringInputExample3 < // main method public static void main(String argvs[]) < // To store the elements of the String array argvs String str = ""; // Calculating the size of the String array int size = argvs.length; // loop for iterating over the elements of the String array argvs for(int i = 0; i < size; i++) < // Converting the String array into a string str = str + argvs[i] + " "; >// displaying the entered string System.out.print("The string entered by the user is: " + str ); > >

String Input in Java 1

Explanation: The command line argument is put when the program is executed using the java command. The number of elements in the String array argvs[] is decided by the white spaces present in the input string. In the input string (“My name is Khan”), there are three white spaces present. Hence, there are four string elements present in the array argvs (“My”, “name”, “is”, “Khan”). The array argvs is then parsed using the for-loop, and elements of the array argvs are then concatenated to build the string again, as we have shown in the above output.

Источник

String Input in Java

Java Course - Mastering the Fundamentals

With the help of the I/O package, Java has several Streams that help the user in performing all the input-output activities. These streams support all types of objects, data types, characters, and so on.

For taking string input we can make use of various methods like using Scanner class, BufferedReader class, and Command Line argument.

How to Take String Input in Java ?

Input and Output are one of the most important parts of learning any programming language. Java has a various number of I/O Streams that help the user in performing all the input-output activities, taking string input from the user can be done using these I/O streams. Further in this article, we will discuss all those approaches that are needed to be followed for taking string input.

Method — 1 : By Using Java Scanner Class

The Scanner class is provided by the java.util package and is used to take input from the user. The Scanner class has the following methods that help us to take input from the user :

For using the Scanner class, we have to import the Scanner Class in our code by using the following syntax :

Now let’s see how these methods help us to take string input in Java.

Scanner.nextLine() Method

The Scanner class’s nextLine() method is used to take string input from the end user. nextLine() method is contain java.util.Scanner class. This method reads text until it reaches the end of the line. It moves the cursor to the next line after reading the line.

The skipped line is returned by the nextLine() method. It doesn’t take any parameters. When the nextLine() method can’t find a line, it throws a NoSuchElementException. If the scanner class is closed, it also throws an IllegalStateException.

Now let’s take a look at an example of the nextLine() method :

In this example, we are importing the scanner class using the nextLine() method followed by System.in standard input stream

In this example, we are showing the case when this method throws NoSuchElementException.

We haven’t provided any std input to our java program, so it will throw NoSuchElementException.

Scanner.next() Method

The Scanner class’s next() method in Java is used to read the input before the whitespace is detected. next() method is unable to read two words separated by whitespace. After reading the input, it keeps the pointer in the same line.

Next complete string value is returned by next() method. It doesn’t take any parameters. When the next() method can’t find string value, it throws a NoSuchElementException. If the scanner class is closed, it also throws an IllegalStateException.

Now let’s take a look at an example of the next() method :

In this example, we are importing the scanner class for using the next() method followed by System.in standard input stream

In this example, we are showing the case when this method throws NoSuchElementException.

We haven’t provided any std input to our java program, so it will throw NoSuchElementException.

Difference Between Scanner.nextLine() and Scanner.next()

The key difference between the nextLine() and next() method is that the next() method gets terminated when whitespace is encountered, whereas the nextLine() method terminates only when enter is pressed and next line is reached.

Method — 2 : By Using Java BufferedReader Class

The BufferedReader class is provided by the java.io package and is used to read the stream of characters, BufferedReader accepts the InputStreamReader class as the parameter for its execution.

Some basic differences between Scanner class and BufferedReader class :

  • BufferedReader is synchronous while the Scanner is not. So, BufferedReader should be used if we are working with multiple threads.
  • BufferedReader has a significantly larger buffer memory than Scanner.
  • BufferedReader is slightly faster than the scanner since the scanner parses the input data, whereas BufferedReader reads a sequence of letters.

BufferedReader class has the readLine() method for taking string input from the user. readLine() method reads a single line at a time.

The readline() method returns the line that the user has entered. Now let’s take a look at an example of how the BufferedReader class is used for taking string input.

In this example, we are using BufferedReader with InputStreamReader for the standard IO stream, also BufferedReader must be used inside the try-catch block in case of exceptions.

Method — 3 : By Using the Command Line Arguments

In Java programs, we can pass the command line argument in the main method of the driver program.

String args[] is a string array that takes a line as an input. So, we can pass a string as an argument to the main method and can fetch its value and use it.

In this example, we have used the command line argument using the args[] array and used its value for displaying the string output.

Command Line Argument :

Conclusion

Оцените статью