Reading Integers from User Input
Stryg for at vise menuen
When you want to read an integer from the user in Java, you use the nextInt() method from the Scanner class. This method reads the next input token as an integer, allowing you to easily prompt the user for numbers such as age, quantity, or any other whole number value. The nextInt() method is a key part of handling numeric input in command-line Java applications.
Main.java
123456789101112131415package 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 age: "); int age = scanner.nextInt(); System.out.println("You entered: " + age); scanner.close(); } }
When you use nextInt() to read input, the program expects the user to enter a valid integer. If the user enters something that is not an integer, such as a word or a decimal number, the Scanner will throw an InputMismatchException. This means your program will stop running unless you handle this situation. It is important to be aware of this behavior so you can design your program to deal with unexpected input gracefully.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat