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

bookReading Strings from User Input

Sveip for å vise menyen

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?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 3
some-alt