我的程序工作正常,但用户仍然可以输入会破坏程序的字符串/字符,从而导致错误。
我想编写一个语句,以便当用户输入 0-100 之间的整数以外的任何内容时,都会显示一条错误消息(基本上我的字符串表明他们不能这样做),或者最好他们根本无法输入除整数之外的任何内容(如果可能的话)。
这是我的代码:
int[] cw_Mark = new int[6];
for (int i = 0; i < cw_Mark.length; i++) {
if (i >= 0 || i <= 100) {
System.out.println("Please Enter Your Module " + (i+1) + " Coursework Mark: ");
cw_Mark[i] = input.nextInt();
} else {
System.out.println("Please Enter a Number Between 1 and 100");
}
}
最佳答案
将其封装在一个方法中 - 如下所示..然后使用该方法从用户处获取整数。
public static int getInt() {
System.out.print("Please enter an integer");
if (console.hasNext("stop")) {
System.out.println("***Terminated***");
System.exit(0);
}
while(!console.hasNextInt()) {
System.out.print("Input is not a valid integer!");
console.next();
}
int temp = console.nextInt();
while(temp<0 && temp>100) {
System.out.println("invalid input");
temp = console.nextInt();
}
return temp;
}
编辑:
如果使用这种方法而不是 try-catch block ,这就是整个解决方案。
package standard;
import java.util.Scanner;
public class Main {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] cw_Mark = new int[6];
for (int i = 0; i < cw_Mark.length; i++) {
System.out.println("Please Enter Your Module " + (i + 1)
+ " Coursework Mark: ");
cw_Mark[i] = getInt();
}
}
//Gets the next integer from the console.
public static int getInt() {
System.out.print("Please enter an integer");
if (console.hasNext("stop")) {
System.out.println("***Terminated***");
System.exit(0);
}
while (!console.hasNextInt()) {
System.out.print("Input is not an integer!");
console.next();
}
int temp = console.nextInt();
while (temp <= 0 && temp >= 100) {
System.out.println("Input must be between 0 and 100");
temp = console.nextInt();
}
return temp;
}
}
关于Java - 如何阻止用户输入整数以外的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19818269/