Reading input with Scanner and week 2 review
So far your programs always did the same thing, because the data was written inside the code. A useful program asks the user and reacts to the answers. In Java the simplest way to read from the keyboard is the Scanner class, which comes in the java.util package. In this lesson you will use it and then review everything from week 2.
Your first interactive program
To use Scanner you must import it with import java.util.Scanner; at the top of the file and create an object that reads from System.in, the standard input. Then you call nextLine() to read a whole line, nextInt() for an integer and nextDouble() for a decimal. When you finish, close it with close() (or use try-with-resources, which you will see later). If the user types something that is not a number when you expect an integer, Scanner throws InputMismatchException.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Your name: ");
String name = in.nextLine();
System.out.print("First number: ");
int a = in.nextInt();
System.out.print("Second number: ");
int b = in.nextInt();
System.out.println("Hello, " + name + "!");
System.out.println(a + " + " + b + " = " + (a + b));
System.out.printf("Average: %.1f%n", (a + b) / 2.0);
in.close();
}
}
// Typing Ana, 5 and 7 prints:
// Hello, Ana!
// 5 + 7 = 12
// Average: 6.0The nextInt and nextLine trap
There is a classic problem. When you type 5 and press Enter, nextInt() reads the 5, but the line break stays pending in the buffer. If you then call nextLine(), it reads the rest of the current line, which is empty, and it looks like the program skips your question. The fix is to call nextLine() one extra time to consume that line break, or to read everything as text with nextLine() and convert with Integer.parseInt.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// A Scanner over a String simulates a user typing "5", Enter, "Ana", Enter
Scanner in = new Scanner("5\nAna\n");
int age = in.nextInt();
String broken = in.nextLine(); // reads the empty rest of line 1
System.out.println("[" + broken + "]"); // []
String name = in.nextLine(); // now reads Ana
System.out.println(age + " " + name); // 5 Ana
// Safer approach: read text and convert
Scanner in2 = new Scanner("42\n");
int value = Integer.parseInt(in2.nextLine().trim());
System.out.println(value + 1); // 43
}
}Week 2 review
- Operators: + - * / %, shortcuts += and ++, comparisons that give boolean, && || ! with short-circuit.
- Conversions: automatic widening, explicit cast that truncates, integer overflow.
- String: immutable, methods length, charAt, substring, indexOf, replace, split; compare with equals.
- format, text blocks and StringBuilder to build text.
- Scanner: nextLine, nextInt, nextDouble and the line break trap.
A good interactive program validates what it receives. A user can type letters where you expect a number, leave the line empty or type an absurd value such as a negative age. Later you will learn to catch exceptions and to repeat the question with a loop, but from now on adopt the habit of asking clearly ("Age between 0 and 120:") and of not trusting outside data blindly. Everything that comes in from the outside must be treated as potentially wrong.
检验所学
第 1 / 6What does 17 % 5 return?
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符