Java - 如何阻止用户输入整数以外的内容?

标签 java arrays loops if-statement java.util.scanner

我的程序工作正常,但用户仍然可以输入会破坏程序的字符串/字符,从而导致错误。

我想编写一个语句,以便当用户输入 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/

相关文章:

java - 如何在 hadoop 文件系统上为 Java 程序设置类路径

java - 在android中添加两个字节数组

javascript - 如何在 NodeJS 中展开对象数组?

java - 如何将局部变量设置为作为方法参数传入的类型

java - Java 中的完整 LaTeX 解析器

java - 尝试插入方法时出现多键错误

javascript - 按字符串内的数字对数组进行排序

javascript - 在 Javascript 中制作数字表程序(如 12 x 1 = 12)时出现问题

java - 在 Wicket 口中创建带有循环的链接列表

javascript - 使用await函数循环抛出错误