Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import java.util.InputMismatchException; import java.util.Scanner; // File: BasicIO.java - demonstrates Scanner input and formatted output public class BasicIO { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("=== Java Basic I/O Demo ==="); System.out.print("Enter your name: "); String name = scanner.nextLine(); int age = 0; boolean valid = false; while (!valid) { System.out.print("Enter your age: "); try { age = scanner.nextInt(); if (age < 0 || age > 150) { System.out.println("Age must be between 0 and 150. Try again."); } else { valid = true; } } catch (InputMismatchException e) { System.out.println("Please enter a whole number."); scanner.nextLine(); // discard bad input } } // Formatted output using printf System.out.printf("%nHello, %s! You are %d years old.%n", name, age); System.out.printf("In 10 years you will be %d.%n", age + 10); scanner.close(); // always close resources } }
Result
Open