Java 如何制作输入验证的方法
我的教授有一个关于输入的东西,主输入不能超过30行,但他希望我们验证输入。我正在制作一个矩形的子类,所以我主要是用这个来获取矩形的参数Java 如何制作输入验证的方法,java,validation,loops,Java,Validation,Loops,我的教授有一个关于输入的东西,主输入不能超过30行,但他希望我们验证输入。我正在制作一个矩形的子类,所以我主要是用这个来获取矩形的参数 Scanner input = new Scanner(System.in); System.out.println("Enter the X coordinate (Upper Left bound):"); int x = input.nextInt(); System.out.println("Enter the Y coord
Scanner input = new Scanner(System.in);
System.out.println("Enter the X coordinate (Upper Left bound):");
int x = input.nextInt();
System.out.println("Enter the Y coordinate (Upper Left bound):");
int y = input.nextInt();
System.out.println("Enter the width of the rectangle: ");
int width = input.nextInt();
System.out.println("Enter the height of the rectangle: ");
int height = input.nextInt();
BetterRectangle rectangle = new BetterRectangle(x, y, width, height);
他想让我们在另一个类中创建一个方法来使用hasNextInt进行验证,但我不确定如何实现一个方法来验证来自主类的输入,或者我必须移动它从主类获取输入的方式吗?为什么不能有一个将
扫描仪输入作为参数的方法
public int getNext (Scanner input, String prompt) {
System.out.println (prompt);
if (input.hasNextInt ()) {
return input.nextInt ();
}
// return some magic number or maybe throw exception
return Integer.MIN_VALUE;
}
更新了@laune的绝妙创意
这可以用作
int x = getNext (input, "Enter the X coordinate (Upper Left bound):");
int y = getNext (input, "Enter the Y coordinate (Upper Left bound):");
int w = getNext (input, "Enter the width of the rectangle: ");
int h = getNext (input, "Enter the height of the rectangle:");
为什么不能有一个将扫描仪
输入
作为参数的方法
public int getNext (Scanner input, String prompt) {
System.out.println (prompt);
if (input.hasNextInt ()) {
return input.nextInt ();
}
// return some magic number or maybe throw exception
return Integer.MIN_VALUE;
}
更新了@laune的绝妙创意
这可以用作
int x = getNext (input, "Enter the X coordinate (Upper Left bound):");
int y = getNext (input, "Enter the Y coordinate (Upper Left bound):");
int w = getNext (input, "Enter the width of the rectangle: ");
int h = getNext (input, "Enter the height of the rectangle:");
只需通过引用传递输入,或将输入传递给返回矩形或异常的方法。添加验证方法(在实例级别)然后在BetterRectangle
的构造函数中调用它来验证输入。id必须将输入移动到类中,而不是在main中?只需通过引用传递输入或将输入传递到返回矩形或异常的方法。添加验证方法(在实例级别)然后在BetterRectangle
的构造函数中调用它来验证输入。id必须将输入移到类中,而不是移到主类中?可能会一直这样做,并将提示添加到此方法。@laune您希望是我的某物或其他。但是,我如何获得4个不同的参数?请参阅我的更新。这个方法可能在你的main
类中,甚至在你的BetterRectangle
类中是一个静态方法,我不知道你是否还能看到这个,但它不允许我在tester类的main中使用这个方法,它说该方法不存在,可能会一直存在并向该方法添加提示。@laune您希望是我的某物或其他。但是我如何获得4个不同的参数?请参阅我的更新。这个方法可能在你的main
类中,甚至是BetterRectangle
类中的一个静态方法。我不知道你是否还会看到这个,但它不允许我在tester类的main中使用这个方法,它说这个方法不存在