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

bookReading Strings from User Input

Desliza para mostrar el menú

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?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 1. Capítulo 3
some-alt