Introduction
Input and output let a program talk with people. Input lets the program get information from users. Output shows results back to users.
Input and output let a program talk with people. Input lets the program get information from users. Output shows results back to users.
import java.util.Scanner; // To get input from user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); // To show output to user System.out.println("Your input was: " + input); scanner.close();
Use Scanner to read input from the keyboard.
Use System.out.println() to print output on the screen.
Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.println("You are " + age + " years old."); scanner.close();
Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); scanner.close();
This program asks the user for their favorite color and then shows it back.
import java.util.Scanner; public class InputOutputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your favorite color: "); String color = scanner.nextLine(); System.out.println("Your favorite color is " + color + "."); scanner.close(); } }
Always close the Scanner after use to free resources.
Input and output make programs interactive and useful.
Input lets programs get information from users.
Output lets programs show results or messages.
Together, they make programs interactive and helpful.
input from users?import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("You are " + age + " years old.");
}
}25import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number: ");
int num = sc.nextLine();
System.out.println("Number is " + num);
}
}Pass the test and this pattern moves unknown