О циклах while и if, вложенных в операторы - PullRequest
0 голосов
/ 25 сентября 2019

Я работаю над этим проектом, который называется «Репетитор по алгебре» для моего самого первого Java-класса.

Программа должна иметь возможность вывести вопрос, чтобы решить, хотите ли вы решить для m или b или y в формуле y = mx + b.

Один разиз них выбрать по номеру: «Выберите 1, чтобы Решить для Y, 2, чтобы Решить для M, 3, чтобы Решить для B и 4, чтобы выйти."

Это должно датьВы выход, чтобы решить формулу.

Я работаю в части 3 проекта, которая:

Обновите вашу программу так, чтобы каждый режим типа проблемы неоднократно задавал вопросы, пока пользователь не получит 3 правильныхответы подряд.

Если выполняется попытка более 3-х вопросов в определенном режиме, программа должна предоставить подсказку о том, как решать проблемы этого типа.

После того, как ученик правильно ответил3 вопроса подряд, должен отображаться общий балл (количество правильно ответивших вопросов, разделенное на общее количество попыток ответить на вопросы), и снова отображается меню.

Итак, яЯ застрял на том, как я могу разместить счетчик, который начинается с 0, и каждый раз, когда пользователь отвечает правильно, тогда 1 будет добавлен к счетчику и выйдет, если он получит 3 подряд или вернется к 0, если пользователь ответит неправильно.

Я предоставлю свой код. Я запутался в том, как использовать цикл while внутри оператора if, а затем еще один цикл while длясчет, это сбивает с толку, я знаю, но как только вы увидите мой код, вы поймете, о чем я говорю.

Итак, я знаю, что могу разместить счетчик следующим образом:

int counter = 0;
while (counter < 4) 
      if statement here 
       counter ++; 
      else 
        counter = 0;
import java.util.Scanner;

class AlgebraTutor {

    public static void main(String[] arg) {
        double min_value = -100;
        double max_value = 100;

        double m_value = generate_random(max_value, min_value);
        double x_value = generate_random(max_value, min_value);
        double b_value = generate_random(max_value, min_value);
        double y_value = generate_random(max_value, min_value);
        Scanner user_input = new Scanner(System.in);
        int user_answer_int = 0;

        while ((user_answer_int < 4) && (user_answer_int >= 0)) {
            System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
            user_answer_int = user_input.nextInt();
            if (user_answer_int == 1) {
                check_answer_for_y(m_value, x_value, b_value);
            }
            else if (user_answer_int == 2) {
                check_answer_for_m(x_value, y_value, b_value);
            }
            else if (user_answer_int == 3) {
                check_answer_for_b(m_value, x_value, y_value);
            }
            else {
                System.out.println("You are done");
            }

        }
    }

    static void check_answer_for_m(double x_value, double y_value, double b_value) {
        System.out.println("Solve For M Problem ");
        System.out.println("Given: ");
        System.out.println("b = " + b_value);
        System.out.println("x = " + x_value);
        System.out.println("y = " + y_value);

        System.out.print("What is the value of m? ");
        Scanner user_input = new Scanner(System.in);
        String user_answer_m = "";
        user_answer_m = user_input.next();
        int user_answer_int = Integer.parseInt(user_answer_m);

        int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);

        if (user_answer_int == correct_answer_m){
            System.out.println("You are correct!");
        } else {
            System.out.print("Sorry, that is incorrect. ");
            System.out.println("The answer is " + correct_answer_m);

        }

    }
    static void check_answer_for_b(double m_value, double x_value, double y_value) {
        System.out.println("Solve For B Problem ");
        System.out.println("Given: ");
        System.out.println("m = " + m_value);
        System.out.println("x = " + x_value);
        System.out.println("y = " + y_value);

        System.out.print("What is the value of b? ");
        Scanner user_input = new Scanner(System.in);
        String user_answer_b = "";
        user_answer_b = user_input.next();
        int user_answer_int = Integer.parseInt(user_answer_b);

        int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));

        if (user_answer_int == correct_answer_b){
            System.out.println("You are correct!");
        } else {
            System.out.print("Sorry, that is incorrect. ");
            System.out.println("The answer is " + correct_answer_b);

        }
    }

    static void check_answer_for_y(double m_value, double x_value, double b_value) {
        System.out.println("Solve For Y Problem ");
        System.out.println("Given: ");
        System.out.println("m = " + m_value);
        System.out.println("x = " + x_value);
        System.out.println("b = " + b_value);

        System.out.print("What is the value of y? ");

        Scanner user_input = new Scanner(System.in);
        String user_answer_y = "";
        user_answer_y = user_input.next();
        int user_answer_int = Integer.parseInt(user_answer_y);

        int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;

        if (user_answer_int == correct_answer_y) {
            System.out.println("You are correct!");
        } else {
            System.out.print("Sorry, that is incorrect. ");
            System.out.println("The answer is " + correct_answer_y);

        }
    }
    static int generate_random(double max_value, double min_value) {

        return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
    }
}

Где я указал цикл while для числа, введенного пользователем, в зависимости от числа, тогда оператор if переходитгде я могу разместить свой счетчик для запуска и перехватить все операторы if в зависимости от числа, которое выберет пользователь, а затем, если пользователь получит 3 правильных слова подряд, программа должна вернуться к основному вопросу.Могу ли я сделать еще один цикл внутри того, что у меня уже есть?Или я должен поместить его внутри каждого оператора if?

1 Ответ

0 голосов
/ 25 сентября 2019

Поместите здесь цикл для каждого

else if (user_answer_int == 3) {
        check_answer_for_b(m_value, x_value, y_value);
    }

, меняющего свою основную функцию на эту.

     public static void main(String[] arg) {

    double min_value = -100;
    double max_value = 100;

    double m_value = generate_random(max_value, min_value);
    double x_value = generate_random(max_value, min_value);
    double b_value = generate_random(max_value, min_value);
    double y_value = generate_random(max_value, min_value);
    Scanner user_input = new Scanner(System.in);
    int user_answer_int = 0;

    while ((user_answer_int < 4) && (user_answer_int >= 0)) {
      System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
      user_answer_int = user_input.nextInt();
      int i = 0;
      if (user_answer_int == 1) {
        while (i < 3){
          if (check_answer_for_y(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
            i++;
          }
          else {
            i = 0;
          }
        }
      }
      else if (user_answer_int == 2) {
        while (i < 3){
          if (check_answer_for_m(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
            i++;
          }
          else {
            i = 0;
          }
        }
      }
      else if (user_answer_int == 3) {
        while (i < 3){
          if (check_answer_for_b(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
            i++;
          }
          else {
            i = 0;
          }
        }
      }
      else {
        System.out.println("You are done");
      }
    }
  }
  static boolean check_answer_for_m(double x_value, double y_value, double b_value) {
    System.out.println("Solve For M Problem ");
    System.out.println("Given: ");
    System.out.println("b = " + b_value);
    System.out.println("x = " + x_value);
    System.out.println("y = " + y_value);

    System.out.print("What is the value of m? ");
    Scanner user_input = new Scanner(System.in);
    String user_answer_m = "";
    user_answer_m = user_input.next();
    int user_answer_int = Integer.parseInt(user_answer_m);

    int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);

    if (user_answer_int == correct_answer_m){
      System.out.println("You are correct!");
      return true;
    } else {
      System.out.print("Sorry, that is incorrect. ");
      System.out.println("The answer is " + correct_answer_m);
      return false;

    }

  }
  static boolean check_answer_for_b(double m_value, double x_value, double y_value) {
    System.out.println("Solve For B Problem ");
    System.out.println("Given: ");
    System.out.println("m = " + m_value);
    System.out.println("x = " + x_value);
    System.out.println("y = " + y_value);

    System.out.print("What is the value of b? ");
    Scanner user_input = new Scanner(System.in);
    String user_answer_b = "";
    user_answer_b = user_input.next();
    int user_answer_int = Integer.parseInt(user_answer_b);

    int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));

    if (user_answer_int == correct_answer_b){
      System.out.println("You are correct!");
      return true;
    } else {
      System.out.print("Sorry, that is incorrect. ");
      System.out.println("The answer is " + correct_answer_b);
      return false;
    }
  }

  static boolean check_answer_for_y(double m_value, double x_value, double b_value) {
    System.out.println("Solve For Y Problem ");
    System.out.println("Given: ");
    System.out.println("m = " + m_value);
    System.out.println("x = " + x_value);
    System.out.println("b = " + b_value);

    System.out.print("What is the value of y? ");

    Scanner user_input = new Scanner(System.in);
    String user_answer_y = "";
    user_answer_y = user_input.next();
    int user_answer_int = Integer.parseInt(user_answer_y);

    int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;

    if (user_answer_int == correct_answer_y) {
      System.out.println("You are correct!");
      return true;
    } else {
      System.out.print("Sorry, that is incorrect. ");
      System.out.println("The answer is " + correct_answer_y);
      return false;

    }
  }
  static int generate_random(double max_value, double min_value) {

    return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...