Reading Strings from User Input
Glissez pour afficher le 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
12345678910111213package 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.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion