简体   繁体   English

如何在Java Eclipse中将Enter键作为错误捕获?

[英]How do you catch enter key as an error in java eclipse?

this is what i'm trying to do: 这就是我想要做的:

User enters numbers into the program and program does stuff with it. 用户在程序中输入数字,程序就用它填充。

but if the user were to just type the "enter" key (or "return" key) eclipse says 但是如果用户只是键入“ enter”键(或“ return”键),则eclipse说

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0

what i need for eclipse to say is "invalid input" and ask for the input again. 我需要日食说的是“无效输入”,然后再次要求输入。

This is how i am getting the input: 这就是我获取输入的方式:

I am using one buffered reader in one function, and i am calling the function whenever i need to read input from the user. 我在一个函数中使用一个缓冲的读取器,并且每当我需要从用户那里读取输入时,就会调用该函数。 Here are my codes for this function incase you want to refer to it. 这是我针对此功能的代码,以备您参考。 Also, the program is a coverage optimization program, incase you wanted to know that as well. 另外,该程序也是覆盖率优化程序,以防您也想知道这一点。 Thank you so much for your help! 非常感谢你的帮助!

public static String Reader() {
  BufferedReader nerd = new BufferedReader(new InputStreamReader(System.in));
  String rvalue = "0";
  try {
    rvalue = nerd.readLine();
    if(elements_typed == 0) {
      Integer.parseInt(rvalue);
    }
    if(sets_typed == 0) {
      Integer.parseInt(rvalue);
    }
    return rvalue; 
  } catch (IOException e) {
    System.out.print("ERROR: Input must be an integer in [1, infinity]!");
    display_menu();
  } catch (NumberFormatException e) {
    System.out.print("ERROR: Input must be an integer in [1, infinity]!\n\n");  
    if(elements_typed == 0) {
      System.out.print("Enter number of elements (n):\n");
      rvalue = Reader();
    }
    if(sets_typed == 0) {
      System.out.print("Enter number of sets (n):\n");
      rvalue = Reader();
    }
  }
  return rvalue;
}

I am not sure without seeing more of your code, but I would do: 我不确定是否看不到您的更多代码,但我会这样做:

while (rvalue.trim().isEmpty())
{
  System.out.println("invalid input");
  rvalue = nerd.readLine();
}

after the rvalue = nerd.readLine(); rvalue = nerd.readLine(); statement 声明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM