【问题标题】:Trying to figure out how to take enter key as user input to signal printMenu()试图弄清楚如何将输入键作为用户输入信号 printMenu()
【发布时间】:2020-10-29 20:29:27
【问题描述】:

我已经编写了以下应用程序,一切正常。然而,在用户输入对应于菜单命令的值(1-7)后,该命令被执行,然后程序终止。我正在尝试找到一种方法,允许我在显示命令结果后要求用户“按 Enter”,以重新打印菜单并继续输入命令,直到它们准备好退出 (8)。这意味着按下回车将重新打印菜单并允许输入更多命令(1-8)。我知道这需要作为一个循环来完成,但我不确定在这种情况下使用哪个/如何使用循环。谢谢。

import java.util.*;
import java.io.*;

public class RosterApplication {

    Scanner in = null;

    public static void main(String[] args) {
        Roster studentRoster = new Roster();
        studentRoster.loadData("assg3_roster.txt");

        printMenu();

        Scanner keyboard = new Scanner(System.in);
        String entry = keyboard.next();

        if (entry.equals("1")) { //Display the roster
            studentRoster.displayRoster();
        }
        //System.out.println("Press enter to continue:");
        //String reload = keyboard.nextLine();
        //if (reload.equals("")) {
        //  printMenu();
        //}
        if (entry.equals("2")) { //Search for a student by id
            System.out.println("Please enter the student id to search: ");
            String searchId = keyboard.next();
            if ((studentRoster.searchForStudent(searchId)) == null) {
                System.out.println("Student not found!");
            }

        }
        if (entry.equals("3")) { //Add a new student
            System.out.println("Please enter the student id to add: ");
            String addId = keyboard.next();
            if (studentRoster.searchForStudent(addId) != null) {
                System.out.println("Error: This student already exists! Student's info displayed above." + "\n");
            } else {
                System.out.println("Please enter the student name: ");
                String addName = keyboard.next() + " " + keyboard.next();
                System.out.println("Please enter the student standing: ");
                String addStanding = keyboard.next();
                System.out.println("Please enter the student major: ");
                String addMajor = keyboard.next();
                studentRoster.addStudent(addId, addName, addStanding, addMajor);
                System.out.println("The entered information has succesfully been added as a new student." + "\n");
            }

        }
        if (entry.equals("4")) { //Remove a student
            System.out.println("Please enter the student id to remove: ");
            String removeId = keyboard.next();
            studentRoster.removeStudent(removeId);
        }
        if (entry.equals("5")) { //Search for student by major
            System.out.println("Please enter the major to search: ");
            String majorSearch = keyboard.next();
            ArrayList < Student > students = studentRoster.getStudentByMajor(majorSearch);
            if (students.size() != 0) {
                System.out.println("The students with this major are listed above.");
            } else {
                System.out.println("Error: There are no students with this major!");
            }
        }
        if (entry.equals("6")) { //Sort and save to file
            studentRoster.Sort();
            studentRoster.Save();
        }
        if (entry.equals("7")) { //Save to file
            studentRoster.Save();
        }
        if (entry.equals("8")) { //Exit
            studentRoster.Save();
            System.exit(0);
        }
        
        keyboard.close();
    }

    private static void printMenu() {
        System.out.println("1. Display the roster");
        System.out.println("2. Search for a student by id");
        System.out.println("3. Add a new student");
        System.out.println("4. Remove a student");
        System.out.println("5. Search for students by major");
        System.out.println("6. Sort and save to file");
        System.out.println("7. Save to file");
        System.out.println("8. Exit");
    }
}

【问题讨论】:

  • 因为无论如何你都以System.exit() 退出(虽然这是一个坏习惯),你可以在整个while(true) 方法周围放置一个大循环,除了前两行,初始化扫描仪及其关闭。但是,如果您将System.exit() 替换为break; 会更干净,这样扫描仪就会正确关闭。另请查看How to Ask,然后相应地编辑您的标题。 How to get multiple inputs from user 会更合适。
  • 成功了!非常感谢:)下次这是我发布的第一个问题时,我会确保使用更好的标题。
  • edit 你的问题永远不会太迟。
  • 你的问题已经解决了吗?

标签: java loops input menu equals


【解决方案1】:

如 cmets 中所述,在函数周围添加 while-loop 将重复输入循环,直到退出。

public static void main(String[] args) {
    Roster studentRoster = new Roster();
    studentRoster.loadData("assg3_roster.txt");
    Scanner keyboard = new Scanner(System.in);
    
    while (true) {
        printMenu();
        String entry = keyboard.next();

        // all the other if-statements

        if (entry.equals("8")) { //Exit
            studentRoster.Save();
            // System.exit(0);
            // Killing the program is not advised, better just leave the loop and terminate regularly
            break;
        }
    }

    keyboard.close();
}

【讨论】:

    【解决方案2】:

    大约一年前,我一直在寻找可以收听输入、转义、替代等的库。感谢您的问题,我找到了a nice library

    将以下依赖添加到pom.xml(使用maven项目):

        <dependency>
            <groupId>com.1stleg</groupId>
            <artifactId>jnativehook</artifactId>
            <version>2.1.0</version>
        </dependency>
    

    示例代码:

    import org.jnativehook.GlobalScreen;
    import org.jnativehook.NativeHookException;
    import org.jnativehook.keyboard.NativeKeyEvent;
    import org.jnativehook.keyboard.NativeKeyListener;
    
    import java.util.logging.Level;
    import java.util.logging.LogManager;
    import java.util.logging.Logger;
    
    public class GlobalKeyListenerExample implements NativeKeyListener {
        public void nativeKeyPressed(NativeKeyEvent e) {
            System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    
            if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
                try {
                    GlobalScreen.unregisterNativeHook();
                } catch (NativeHookException nativeHookException) {
                    nativeHookException.printStackTrace();
                }
            }
        }
    
        public void nativeKeyReleased(NativeKeyEvent e) {
            System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
        }
    
        public void nativeKeyTyped(NativeKeyEvent e) {
            System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
        }
    
        public static void main(String[] args) {
    
            // Clear previous logging configurations.
            LogManager.getLogManager().reset();
    
            // Get the logger for "org.jnativehook" and set the level to off.
            Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
    
            logger.setLevel(Level.OFF);
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());
    
                System.exit(1);
            }
    
            GlobalScreen.addNativeKeyListener(new GlobalKeyListenerExample());
        }
    }
    

    使用这个库,你可以获得关于点击进入、空格、转义等的信息。上面的例子是完整的,你可以复制并检查它是如何工作的。 Here 是原始示例。
    问你是否有什么不明白的地方;)

    附:
    这里正在检查单击了哪个键。

    if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
        try {
            GlobalScreen.unregisterNativeHook();
        } catch (NativeHookException nativeHookException) {
            nativeHookException.printStackTrace();
        }
    }
    

    【讨论】:

    • 您可以将所有if 替换为switch。代码看起来会更漂亮。
    猜你喜欢
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    相关资源
    最近更新 更多