简体   繁体   English

如何用 do while 在 java 中做一个切换菜单

[英]How to do a switch menu in java with do while

Good day!再会!

This is my switch menu for a project in java!这是我在java中的一个项目的切换菜单!

When I put a diferent letter (letter that it´s not in the switch) I get this error message, and when I try one of the correct letter I get the same error message again:当我输入一个不同的字母(它不在开关中的字母)时,我收到此错误消息,当我尝试其中一个正确的字母时,我再次收到相同的错误消息:

Exception in thread "main" java.util.NoSuchElementException
        at java.base/java.util.Scanner.throwFor(Scanner.java:937)
        at java.base/java.util.Scanner.next(Scanner.java:1478)
        at teste.menu(teste.java:65)
        at teste.main(teste.java:16)

This is my code:这是我的代码:

import java.util.Scanner;

public class teste{
  public static void main(String[] args){

    char ch;
    do {
      ch = menu();
      switch (ch){
        case 'a':
          //String name ="resultado.csv";
          //ReadFile(name);
          break;
        case 'b':
          //WriteFile();
          break;
        case 'c':
          System.out.println("nome");
          break;
        case 'd':
          System.out.println("nome");
          break;
        case 'e':
          System.out.println("nome");
          break;
        case 'f':
          System.out.println("nome");
          break;
        case 'g':
          System.out.println("nome");
          break;
        case 'h':
          System.out.println("nome");
          break;
        default:
          System.out.println("a-k!");
          break;
      }
    }while (ch != 'k');

    System.exit(0);

  }

  public static char menu(){
    System.out.println("Chose: ");
    System.out.println("a: Show");
    System.out.println("b: Write");
    System.out.println("c: All Numbers Are the Same");
    System.out.println("d: Sum Between Two Integers");
    System.out.println("e: Repeat the String");
    System.out.println("f: It is Palindrome");
    System.out.println("g: Display");
    System.out.println("h: Display");
    System.out.println("k: Quit");
    System.out.println("Insira a opção: ");
    Scanner input = new Scanner(System.in);
    char ch = input.next().charAt(0);
    input.close();
    return ch;
  }

}

I tryed with numbers and I got the same error message我尝试使用数字,但收到相同的错误消息

Don't recreate the scanner each time menu is called.每次调用menu时不要重新创建扫描仪。 Create it once at start of main and use it, such as:在 main 开始时创建一次并使用它,例如:

public static Scanner input = new Scanner(System.in);

public static void main(String[] args) {
    // same code...until end of main...
    input.close();
    System.exit(0);
}

and in menu :menu中:

public static char menu() {
    // same prompts...

    //REMOVE    Scanner input = new Scanner(System.in);
    char ch = input.next().charAt(0);
    //REMOVE    input.close();
    return ch;
}

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

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