Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Reading Strings from User Input | Getting Started with Scanner
Java User Input Essentials

bookReading Strings from User Input

Scorri per mostrare il menu

To read a full line of text from the user in Java, you use the nextLine() method of the Scanner class. This method captures everything the user types until they press Enter, including spaces, tabs, or any other characters. This makes it ideal for reading names, addresses, or any input where spaces may appear. Before you can use nextLine(), you need to create a Scanner object that reads from System.in, which represents keyboard input.

Main.java

Main.java

copy
12345678910111213
package com.example; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); } }

The nextLine() method reads all characters entered by the user until the Enter key is pressed, returning the entire line as a String. Unlike methods such as next(), which only reads up to the first space, nextLine() preserves all spaces and characters in the input. This is especially useful when you want to capture multi-word responses, such as full names or sentences. Common use cases for nextLine() include collecting user comments, addresses, or any input where a single word is not enough.

question mark

Which Scanner method is used to read a full line of text input from the user?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 3
some-alt