importjava.util.Scanner;publicclassInputChecker{privateScannerinput;publicInputChecker(){input=newScanner(System.in);}publicintgetNextInt(Stringprompt){System.out.println...
import java.util.Scanner;
public class InputChecker
{
private Scanner input;
public InputChecker()
{
input = new Scanner(System.in);
}
public int getNextInt(String prompt)
{
System.out.println(prompt);
int number = 0;
while(!input.hasNextInt())
{
System.out.println("That was not an integer.");
System.out.println(prompt);
input.nextLine();
}
number = input.nextInt();
input.nextLine();
return number;
}
public double getNextDouble(String prompt)
{
System.out.println(prompt);
double number = 0.0;
while(!input.hasNextDouble())
{
System.out.println("That was not a number.");
System.out.println(prompt);
input.nextLine();
}
number = input.nextDouble();
input.nextLine();
return number;
}
}
1.开头的scanner为什么要用private再初始化,不能直接写scanner input = new Scanner(System.in); 吗?
2.getNextInt方法里面,倒数第二行为什么要再加一句input.nextLine(); getNextDouble也倒数第二行也加了这一句。我运行的时候发现不加的话输入错误数值后会自动给出两遍“that was not an integer",加了以后就不会有了。可是我不懂为什么要加在这里?
展开