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 thejava.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 aScanner
object namedscanner
which will be used to read input from the user. - We then prompt the user to enter a string by calling the
System.out.print
ln 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 theinput
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.
Average Rating