-1
這是我的代碼在Java中從控制檯讀取
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Person {
private static final String VALID_NAME = "Please enter a valid name!";
private static final String VALID_ID = "ID must contain integers";
private static final String VALID_ADDRESS = "Please enter a valid adress!";
private static final String VALID_INPUT = "Bad input";
public static Scanner input = new Scanner(System.in);
public static String inputAdress() {
String personAdress = null;
try {
if (input.hasNextLine()) {
personAdress = input.nextLine();
} else {
System.err.println(VALID_ADDRESS);
}
} catch (InputMismatchException e) {
System.err.println(VALID_INPUT);
} catch (NoSuchElementException e) {
System.err.println(VALID_INPUT);
} catch (IllegalStateException e) {
System.err.println(VALID_INPUT);
}
return personAdress;
}
public static long inputID() {
long ID = 0;
try {
if (input.hasNextLong()) {
ID = input.nextLong();
} else {
System.err.println(VALID_ID);
}
} catch (InputMismatchException e) {
System.err.println(VALID_INPUT);
} catch (NoSuchElementException e) {
System.err.println(VALID_INPUT);
} catch (IllegalStateException e) {
System.err.println(VALID_INPUT);
}
return ID;
}
public static String inputName() {
String personName = null;
try {
if (input.hasNextLine()) {
personName = input.nextLine();
} else {
System.err.println(VALID_NAME);
}
} catch (InputMismatchException e) {
System.err.println(VALID_INPUT);
} catch (NoSuchElementException e) {
System.err.println(VALID_INPUT);
} catch (IllegalStateException e) {
System.err.println(VALID_INPUT);
}
return personName;
}
}
public static void main(String[] args) {
personName = Person.inputName();
ID = Person.inputID();
personAdress = Person.inputAdress();
System.out.println(personName + " " + ID + " " + personAdress);
}
的問題是,經過ID = Person.inputID();該程序終止並僅打印名稱和ID。 如果我最後調用inputID沒有問題。我試圖調試並且personAdress收到沒有任何輸入的空字符串。任何想法爲什麼?