How to print a string entered by user?

0 0
Read Time:56 Second

Write a program to print a string entered by user.

import java.util.Scanner;
public class PrintString {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String input = scanner.nextLine();
        System.out.println("You entered: " + input);
    }
}

Output:

Enter a String: CodeDixa
You entered: CodeDixa

Explanation:

  • We start by importing the Scanner class from the java.util package. This will allow us to read input from the user.
  • Next, we define a main method which is the entry point of the program.
  • Inside the main method, we create a Scanner object named scanner which will be used to read input from the user.
  • We then prompt the user to enter a string by calling the System.out.println method to print the message “Enter a string: ” to the console.
  • We then use the scanner.nextLine method to read a line of text from the user, which is stored in the input variable.
  • Finally, we print the input string back to the console using the System.out.println method, along with a message indicating that the user entered that string.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment

Verified by MonsterInsights