219k views
3 votes
Use scnr.nextLine(); to get a line of user input into a string. Output that line.

1 Answer

6 votes

Final answer:

To get a line of user input into a string, use the scnr.nextLine(); method in Java. This method reads the entire line of text entered by the user and stores it as a string.

Step-by-step explanation:

To get a line of user input into a string, you can use the scnr.nextLine() method in Java. This method reads the entire line of text entered by the user until a newline character is encountered, and stores it as a string. Here's an example:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);

System.out.println("Enter a line of text:");
String userInput = scnr.nextLine();

System.out.println("You entered: " + userInput);
}
}

In the example code, the Scanner class is used to create a new scanner object scnr to read user input. The nextLine() method is then called on the scnr object to obtain a line of input, which is stored in the string variable userInput. Finally, the obtained line of input is printed using the System.out.println() method.

User Truly
by
8.3k points