简体   繁体   中英

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

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 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(); statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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