简体   繁体   中英

How to make Java detect keypress in my scenario?

I am writing a program for a project for school. The project requires me to create a record of pets for a pet hospital. I am supposed to create a list of pet owners (maximum of 30 owners) with their first name, last name, e-mail, and phone, and an array pets for each owner (maximum of pets per owner is 5). However, the user can create a list of less than 30 owners. The issue I have is I want to make code where the user can press the escape key to stop the outside while loop that asks them for the owner info when they don't need to add anymore owners. Also, where it says, "System.out.println("Press enter to add another owner or Esc to finish list.");" it is in another loop, so if the user hits an incorrect key it will loop asking them if they want to stop adding tot he list or not (until they hit esc or enter). (Note: the code below is not my whole program, I just needed help with one specific part. I left the if statements blank, because that is where my keypress code will be.).

public class Runner
{
   public static void main(String[]args)
   {
     while(i <= 30)
     {
      System.out.println(i + ". " + "Enter the owner's first name.");
      String first = scan.nextLine();
      System.out.println(i + ". " + "Enter the owner's last name.");
      String last = scan.nextLine();
      System.out.println(i + ". " + "Enter the owner's email address.");
      String emailAdd = scan.nextLine();
      System.out.println(i + ". " + "Enter the owner's phone number.");
      String phone = scan.nextLine();
      Owner owner = new Owner(first, last, emailAdd, phone);
      int j = 1;
      while(j > 0)
        {
           System.out.println("Press enter to add another owner or Esc to 
           finish list.");
           if ()
           {

           }
           if ()
           {

           }
           j++;
        }


     list.add(owner.toString());

     i+=1;
       }
  System.out.println(list);
    }
}

Since Java is merely using the console, there's no native way to detect a single keypress... any input must end with an "enter" to actually be taken by the program.

As such, to emulate detecting an enter keypress you could do something like:

if (scan.nextLine().isEmpty()) 
    // do stuff

Since we know that a line always means that the enter key was pressed, if the String is empty, it means that only the enter key remains.

For the ESC key, you should use a 3rd party library if is imperative to have it work like that, otherwise, you could have the user actually write "ESC" or some other key word defined by you as input.

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