【问题标题】:Validate user input to only accept type int or String "quit"验证用户输入仅接受类型 int 或 String "quit"
【发布时间】:2017-02-25 19:29:48
【问题描述】:

我的代码打印出一个已经声明的数组,然后要求用户输入。用户应该输入 xy 格式的数字或键入 quit 以停止使用该程序。在获得用户输入后,它使用 x 作为行和 y 作为列号打印出数组的元素,然后将该索引设置为 0 并打印新数组。 到目前为止,除了只接受整数或用户“退出”之外,我已经完成了大部分工作。如果用户输入除“退出”之外的另一个字符串,则程序崩溃。 这是我的代码。 导入 java.util.Scanner;

public class Exercise23 {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);

        int [][] array = {
            {0, 1, 4, 5},
            {3, 7, 9, 7},
            {1, 8, 2, 1}
        };

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j]);
            }
            System.out.println();
        }

        boolean exitCon = false;

        do {
            System.out.println("Please enter a number in the format 'xy' with no spaces in between or enter 'quit' to stop");
            String xy = read.nextLine();
            if (!"quit".equals(xy)) {
                String x = xy.substring(0, 1);
                String y = xy.substring(1);
                int row = Integer.parseInt(x);
                int column = Integer.parseInt(y);
                if (0 <= row && 0 <= column && row <= 2 && column <=) {
                System.out.println();
                    System.out.println(array[row][column]);
                    array[row][column] = 0;

                    System.out.println();

                    for (int i = 0; i < array.length; i++) {
                        for (int j = 0; j < array[i].length; j++) {
                            System.out.print(array[i][j]);
                        }
                        System.out.println();
                    }
                    System.out.println();

                } else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");

                }

            } else if (xy.equals("")) {
                System.out.println("You can only enter integers or 'quit'.");               
            } else {
                exitCon= true;   
            }

        } while (!exitCon);

    }
}

问题出在这个位

String xy = read.nextLine();
if (!"quit".equals(xy)) {
    String x = xy.substring(0, 1);
    String y = xy.substring(1);
    int row = Integer.parseInt(x);
    int column = Integer.parseInt(y);
    if (0 <= row && 0 <= column && row <= 2 && column <= 3) {
        System.out.println();
        System.out.println(array[row][column]);
        array[row][column] = 0;

        System.out.println();

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j]);
            }
            System.out.println();
        }
        System.out.println();

        } else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");

        }

    } else if (xy.equals("")) {
            System.out.println("You can only enter integers or 'quit'.");               
    } else {
        exitCon= true;

我收到此错误“线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:1 在 java.lang.String.substring(String.java:1963) 在练习23.main(练习23.java:26) "

【问题讨论】:

  • 崩溃时出现什么错误?
  • 对不起,我忘了添加错误信息。现已编辑。 @史蒂夫101
  • 这意味着您的输入字符串 (next.readLine()) 的长度为零。那么xy.substring(0, 1) 抛出异常
  • 我认为那是因为我尝试了一个空字符串。当我输入其他内容时,它再次崩溃
  • 是的,在没有检查正确输入的情况下做某事有几点。在解析字符串之前,您必须检查它是否输入正确。长度是第一个检查,另一个是检查是否只包含数字。

标签: java validation input user-input


【解决方案1】:

请看代码,这将涵盖案例并且可以简单扩展:

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));
        String s;
        while ((s=br.readLine())!=null) {
            if (s.equals("quit")) {
                break;
            }
            else if (s.matches("\\d{2}")) {
                // parse it (exactly 2 digits)
                System.out.print("parse:"+s);
            }
            else {
                System.out.println("You can only enter 2dig integers or 'quit'.");
            }
        }

【讨论】:

    【解决方案2】:

    谢谢大家。我已经设法根据您的答案和 cmets 的想法解决了我自己的问题。

    我做了这些改变

    if (xy.length() == 2) {
        String x = xy.substring(0, 1);
        String y = xy.substring(1);
        int row = Integer.parseInt(x);
        int column = Integer.parseInt(y);
        if (0 <= row && 0 <= column && row <= 2 && column <= 3) {
        System.out.println();
            System.out.println(array[row][column]);
            array[row][column] = 0;
    
            System.out.println();
    
            for (int i = 0; i < array.length; i++) {
                    for (int j = 0; j < array[i].length; j++) {
                        System.out.print(array[i][j]);
                    }
                    System.out.println();
            }
            System.out.println();
    
            } else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
    
            }
    
    } else if ("quit".equals(xy)) {
            exitCon= true;                              
    } else {
            System.out.println("You can only enter integers or 'quit'.");
    

    【讨论】:

    • 您的解决方案仍然“错误”。考虑输入两个不是数字的字符。这就是为什么您应该非常精确地检查输入。
    • 如何在检查长度后检查它是否只包含数字。毕竟它可以包含字符以使字符串退出工作。 @krzydyn
    • 请看我的回答
    【解决方案3】:

    您的代码的问题是任何不是“退出”的字符串都会进入第一个 if 条件,这就是导致您的代码崩溃的原因。如果提供的字符串是数字,您只想输入第一个条件。你的条件应该是:

    if (StringUtils.isNumeric(xy)) {
    ...
    } else if (!xy.equals("quit")) {
        System.out.println("You can only enter integers or 'quit'.");
    } else {
        exitCon= true;
    }
    

    【讨论】:

    • 我收到错误消息“找不到符号”。使用 StringUtils 时。
    • @UysalM StringUtils.isNumeric() 来自 Apache Commons Lang 库,这是您必须导入的第三方库。我只是用它作为逻辑应该是什么的一个例子(因为.isNumeric(xy) 是非常自我解释的)。重要的部分是检查字符串是否为数字,是否使用第三方库或正则表达式匹配或任何其他方法。
    【解决方案4】:

    添加异常后,这里似乎发生了故障;

    String x = xy.substring(0, 1);
    String y = xy.substring(1);
    

    StringIndexOutOfBoundsException 表示字符串“xy”太短,可能在 readline 上为空白。

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 2018-07-07
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 2012-02-07
      • 2023-03-15
      相关资源
      最近更新 更多