Функция не выполняет do-while l oop ... не возвращается на главную? - PullRequest
0 голосов
/ 29 февраля 2020

У меня есть код для моего класса, в который мы включаем стеки. Программа считывает список имен функций и типов данных, которые go вместе с ними. Затем он позволяет пользователю вводить имя заголовка функции вместе с параметрами. Если имя функции совпадает с одним из прочитанных, и если типы данных совпадают, то имя функции и параметры помещаются в стек, и это предлагает пользователю снова ввести заголовок.

Я пытаюсь заставить его повторить запрос с указанием времени l oop, но он не выполняется. Я не уверен, не передается ли элемент управления обратно на главную после проверки типов данных или есть другая проблема. Возможно, важно отметить, что вызываемые функции хранятся в файле класса, отличном от того, где находится main, и включают в себя функциональную декомпозицию.

    int x = -1;
    do {
        System.out.println("What would you like to do? Enter a number 1-3");
        System.out.println("1.) Call a Function");
        System.out.println("2.) End the Function");
        System.out.println("3.) Exit the Program");
        Scanner input = new Scanner(System.in);
        x = input.nextInt();

        switch(x) {
            case 1:
                System.out.println("Please enter function");
                Scanner scan = new Scanner(System.in);
                String functionHeader = scan.nextLine();
                getName(functionHeader);
            case 2:
                System.out.println("it worked!");
            case 3:
                System.exit(0);
        }
    }while(x != 2);

Последняя функция перед возвращением элемента управления:

     public static void checkFunction(int index) {
          boolean works = true;
          if(inputParamNum != functions[index].numParams) {
              System.out.println("Number of Paramaters do not match. \nThe parameter(s) should be:");
              for(int j = 0; j < functions[index].numParams; j++) {
                  System.out.print(functions[index].params[j] + " ");
              }
              System.exit(0);
          }


          for(int i = 0; i < functions[index].numParams; i++) {
              if(functions[index].params[i].equals("String") && ! 
            (inputParams[i].substring(0,1).equals("\""))) {
                  System.out.println("You did not input a String when a String was expected. \nThe correct parameter(s) for this function are/is:");
                  for(int j = 0; j < functions[index].numParams; j++) {
                       System.out.print(functions[index].params[j] + " ");
                  }
                  System.exit(0);
              }
              else if(functions[index].params[i].equals("char") && !(inputParams[i].substring(0,1).contentEquals("\'"))) {
                  System.out.println("You did not input a char when a char was expected. \nThe correct parameter(s) for this function are/is:");
                  for(int j = 0; j < functions[index].numParams; j++) {
                      System.out.print(functions[index].params[j] + " ");
                  }
                  System.exit(0);
              }
              else if(functions[index].params[i].equals("int")) {
                  try{
                      Integer.parseInt(inputParams[i]);
                  }catch(NumberFormatException e){
                      System.out.println("You did not input an int when an int was expected. \nThe correct parameter(s) for this function are/is:");
                      for(int j = 0; j < functions[index].numParams; j++) {
                          System.out.print(functions[index].params[j] + " ");
                      }
                  }
              }
              else if(functions[index].params[i].equals("float")) {
                  try{
                      Float.parseFloat(inputParams[i]);
                  }catch(NumberFormatException e){
                      System.out.println("You did not input a float when a float was expected. \nThe correct parameter(s) for this function are/is:");
                      for(int j = 0; j < functions[index].numParams; j++) {
                          System.out.print(functions[index].params[j] + " ");
                      }
                  }
              }
          }
          System.out.println("Congrats! you input correctly");
      }

Любые предложения будут великолепны. Спасибо:)

1 Ответ

2 голосов
/ 29 февраля 2020
       switch(x) {
            case 1:
                System.out.println("Please enter function");
                Scanner scan = new Scanner(System.in);
                String functionHeader = scan.nextLine();
                getName(functionHeader);
            case 2:
                System.out.println("it worked!");
            case 3:
                System.exit(0);
       }

Вам не хватает break операторов в вашем коммутаторе. Вы должны использовать хорошую IDE, такую ​​как IntelliJ Idea, потому что она предупредит вас о том, что здесь произойдет сбой.

                case 2:
                    System.out.println("it worked!");
                case 3:
                    System.exit(0);

Без оператора break, если будет выполнен случай 2, провал будет произойдет, и случай 3 также будет выполнен.


Решение:

Вам понадобится break операторов следующим образом:

            case 1:
                System.out.println("Please enter function");
                Scanner scan = new Scanner(System.in);
                String functionHeader = scan.nextLine();
                getName(functionHeader);
                break;
            case 2:
                System.out.println("it worked!");
                break;
            case 3:
                System.exit(0);
                break; //This one is technically unnecessary because it's the final case label.
...