如何验证此代码以便用户只能输入整数?
import java.util.Scanner;
public class TrainTester
{
public static void main(String[] args)
{
boolean retry = true;
while (retry)
{
RailroadCar RRCar = new RailroadCar();
PassengerCarriage PCar = new PassengerCarriage();
GoodsCar GCar = new GoodsCar();
RefrigeratedUnit RUnit = new RefrigeratedUnit();
Scanner sc = new Scanner(System.in);
System.out.println("===================================");
System.out.println("Please enter number between 1 and 4");
int i = sc.nextInt();
if (i == 1)
{
RRCar.calculateTotalWeight();
RRCar.displayDetails();
}
else if (i == 2)
{
System.out.println("Enter the amount of passengers in the carriage");
int temp = sc.nextInt();
PCar.setNOP(temp);
PCar.calculateTotalWeight();
PCar.displayDetails();
}
else if (i == 3)
{
System.out.println("Enter the weight of the goods");
int temp1 = SC.nextInt();
GC.setGW(temp1);
GC.calculateTotalWeight();
GC.displayDetails();
}
else if (i == 4)
{
System.out.println("Enter the weight of the goods");
int temp2 = sc.nextInt();
RUnit.setGWeight(temp2);
System.out.println("Enter the weight of the coolant");
double temp3 = sc.nextInt();
RUnit.setCWeight(temp3);
RUnit.calculateTotalWeight();
RUnit.displayDetails();
}
else
{
System.out.println("=========================================================================================")
System.out.println("Please enter a number from the list below, each number represents the different carriages");
System.out.println(" ");
System.out.println("1. RailRoad Carriage");
System.out.println("2. Passenger Carriage");
System.out.println("3. Goods Carriage");
System.out.println("4. Refrigerated Unit");
System.out.println("=========================================================================================")
}
}
}
}
}
答案 0 :(得分:1)
你可以做这件事:
int yourNumber;
final String i = sc.nextLine();
try {
yourNumber = Integer.valueOf(i);
} catch (NumberFormatException ex) {
//not a number
}
答案 1 :(得分:0)
您可以像这样过滤输入值。
int choice = sc.nextInt();
int i;
try{
i= Integer.parseInt(choice);
}catch(Exception e){
System.out.println("Not an integer");
}
答案 2 :(得分:0)
以下是仅验证正数的示例。
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
或者这是最简单的方法
try {
int i = Integer.parseInt(myString);
if (i < 0) {
// Error, negative input
}
} catch (NumberFormatException e) {
// Error, not a number.
}
答案 3 :(得分:0)
int choice = sc.nextInt();
int i;
try{
i= Integer.parseInt(choice);
}catch(Exception e){
System.out.println("Not an integer");
}
如果数字是整数异常,则不会发生其他明智的异常