我正在尝试制作一个基于Java控制台的基本菜单系统。我设法使第一层工作正常:

public static int menu(){

    //Displays the main menu and handles passing off to next menu.

      Scanner scanner = new Scanner (System.in);
      int selection=0;
      String CDid;
      int i=0;
      int j=0;

      while(i==0) {   //changed while(1) to a value that didn't complain in netbeans
          System.out.println("Please choose an option from the following:");
          System.out.println("[1] Search by CD ID");
          System.out.println("[2] View all CD's in store");
          System.out.println("[3] Quit");
          System.out.println("Choice: ");
          selection=scanner.nextInt();

     switch (selection){

         case 1:System.out.println("Please enter the CD ID:");
              i=1;
              break;

         case 2:System.out.println("List all CD's");
              i=1;
              break;

         case 3:System.out.println("Quiting...");
              System.exit(5);

         default:System.out.println("Your choice was not valid!");

          };

      }
      return selection;
  }


我现在正在尝试使它成为可能,以便当您选择选项[1]时,它接受您输入的下一个字符串并运行showCD()方法。我已经尝试过以前使用的方法,但是由于它是字符串,所以遇到了一些错误。

  public static int menu(){
        //Displays the main menu and handles passing off to next menu.

          Scanner scanner = new Scanner (System.in);
          int selection=0;
          String CDid;
          int i=0;
          int j=0;

          while(i==0) {   //changed while(1) to a value that didn't complain in netbeans
              System.out.println("Please choose an option from the following:");
              System.out.println("[1] Search by CD ID");
              System.out.println("[2] View all CD's in store");
              System.out.println("[3] Quit");
              System.out.println("Choice: ");
              selection=scanner.nextInt();

         switch (selection){

             case 1:System.out.println("Please enter the CD ID:");
                    CDid=scanner.toString();
                      while(j==0) {
                         switch (CDid){
                         case 1:showCD(CDid);
                         j=1;
                         break;

                         default:System.out.println("Your choice was not valid!");

                         }
                      }

                  i=1;
                  break;

             case 2:System.out.println("List all CD's");
                  i=1;
                  break;

             case 3:System.out.println("Quiting...");
                  System.exit(5);

             default:System.out.println("Your choice was not valid!");

              };

          }
          return selection;
      }

最佳答案

听起来像是作业(您应该这样标记)。您正在尝试获取用户输入的下一个字符串,但是您的代码正在调用scanner.toString()。这只会打印出Scanner对象的String表示形式。您可能要改用scanner.nextLine()。请参阅this以供参考。

编辑:此外,只是进一步阅读您的代码,然后尝试打开CDid(它是一个字符串)。您无法在Java中打开字符串(但如果您

10-08 13:07
查看更多