Java菜单带有整数和char

  • 本文关键字:char 整数 菜单 Java java
  • 更新时间 :
  • 英文 :


所以我有此代码:

import java.util.*;
public class Menu
{
public static void main(String[] args){
    new Menu().use();
}
public void use() {
    int choice;
        while ((choice = readChoice()) != 0){
            switch (choice){
                case 1: ; break;                    
                case 2: ; break;
                case 3: ; break;
                case 4: ; break; 
            }
        }
}
private int readChoice(){
Scanner scanner = new Scanner(System.in);
    System.out.println("Main Menu:");
    System.out.println("1. Setting.");
    System.out.println("2. View hardware detail.");
    System.out.println("3. View Log.");
    System.out.println("4. Access Admin Mode.");
    System.out.println("0. Exit the system.");
    System.out.print("Enter a choice: ");
    return scanner.nextInt();
}
}

因此,到目前为止,我应该有一个菜单,该菜单将在用户输入中读取直到用户类型为0。但是,我希望当用户输入时,我希望代码停止,而不是用户输入0(整数)'x'(角色)。有没有办法做到这一点?我是Java的新手。

似乎您想接受混合输入,文本(" x")和整数。

Scanner类具有一些实用程序方法,可以在消耗扫描仪输入之前检测到扫描仪的输入,例如hasNextLine()hasNextInt()。使用这些方法,您可以轻松检测是否输入有效的菜单选择:

if (scanner.hasNextInt()) {
    // It's an integer
    int choice = scanner.nextInt();
    switch (choice) {
        ...
    }
}
else {
    // A scanner input is always parseable as a string
    String choice = scanner.nextLine();
    if (Objects.equals(choice, "x")) {
        // Stop, exit, return, terminate and abort
    }
    else {
        // What happens if the user entered an invalid string?
        // You decide!
    }
}

进一步评论

  • 每次迭代,您都会创建一个新的扫描仪实例。这是不必要的开销。您最好只创建一个扫描仪,然后反复接受输入:

    Scanner scanner = new Scanner(int);
    while (scanner.hasNext()) {
        ...
    }
    
  • 您应该正确格式化代码。错误的凹痕很容易困惑更多的读者,包括您自己。

而不是nextInt(),您可以使用next()。因此,您的选择需要定义为字符串。之后,即使您输入一个类似1或2的数字,此数字也将作为字符串处理。之后,您可以用" 1"one_answers" x"。

您应该使用scanner.nextLine().charAt(0)而不是scanner.next().charAt(0),因为接下来不会呈现Newline字符,并且可以跳过您的新输入

相关内容

最新更新