简体   繁体   English

连续3次正确回答问题后,如何将程序循环回到开头/并添加差异

[英]How would I loop my program back to the beginning after a question was answered correctly 3 times in a row/ and add variance

I'm creating a program to help with students solving y= m(x) + b. 我正在创建一个程序来帮助学生解决y = m(x)+ b。 As of right now, I have the program to display the menu and evaluate if your response is correct to the answer. 截至目前,我已经有程序可以显示菜单并评估您的回答是否正确。 However, I need it to also count the number of correct answers in a row. 但是,我还需要它来连续计算正确答案的数量。

  • If 3 correct end program and output total correct out of attempts tried. 如果3正确的结束程序并输出总计正确的尝试次数。
  • else if there were 3 attempts made the output a tip. 否则,如果有3次尝试,则输出为小费。

The main issue I'm having is the loop of the two (methods?). 我遇到的主要问题是两者的循环(方法?)。 I apologize in advance if my code is atrocious, I'm having a hard time understanding methods and classes in this compared to how Python is. 如果我的代码很糟糕,我会提前道歉,与Python相比,我很难理解其中的方法和类。 Anyone's suggestions or tips would be immensely helpful. 任何人的建议或技巧都将大有帮助。

So far I've tried adding methods, and attempts at classes to certain parts of the program such as 到目前为止,我已经尝试添加方法,并尝试在程序的某些部分使用类,例如

public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {}

and

public static test_input() {}

However, now I'm facing scoping problems as well as errors referencing certain variables. 但是,现在我面临范围界定问题以及引用某些变量的错误。

package algebra_Tutor;
import java.util.Scanner;
class AlgebraTutor {

public static void main(String[] args){
    System.out.println("Enter 1 if you would like to solve for Y?");
    System.out.println("Enter 2 if you would like to solve for M?");
    System.out.println("Enter 3 if you would like to solve for B?");
    System.out.println("Enter 4 to Quit");


    //Asks for user input
    System.out.print("Enter your selection: ");
    }

    //Creates random # for values in formula
    int y_ = point_of_line_cross;
    int m_ = slope;
    int b_ = y_intercept; 
    int x_ = independent_variable;

public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {

            // Creates scanner for input of menu Def as menu selector
    Scanner user_Selection = new Scanner(System.in);

            //Converts user input to an integer
    int selection = user_Selection.nextInt();
    user_Selection.close();

    y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
    slope = (int) Math.floor(Math.random() * 201) - 100;
    point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
    independent_variable = (int) Math.floor(Math.random() * 201) - 100;

            //Tests what user input was, with expected output
    if (selection  == (1)) {
        System.out.println("You chose to solve for Y: ");
        System.out.println("Y = " +slope +"("+independent_variable+")"+" + "+y_intercept);
        System.out.println("Input your answer: ");
        }
    else if (selection == (2)) {
        System.out.println("You chose to solve for M: ");
        System.out.println("M = "+"("+point_of_line_cross+" - "+y_intercept+")"+" / "+independent_variable);
        System.out.println("Input your answer: ");
        }
    else if (selection == (3)) {
        System.out.println("You chose to solve for B: ");
        System.out.println("B = "+point_of_line_cross+" - "+slope+"("+independent_variable+")");
        System.out.println("Input your answer: ");
        }
    else if (selection == (4)) {
        System.out.println("You chose to quit the program. ");
    return;
        }
        }
//Solves the problem in order to compare to User input
    int answer_y = ((m_) * (x_)) + (b_);
    int answer_m =(y_) - ((b_) / (x_));
    int answer_b =(y_) - ((m_)* (x_));
public static test_input() {
        //Problem solver defined
    Scanner answer_input = new Scanner(System.in);
    int answer = answer_input.nextInt(); 
        //Creates loop for program
    var counter = 0;
    int correct = 0;
    var answers_correct = false;
    while (!answers_correct && correct < 3) {
        if (answer == answer_y){
            counter++;
            correct++;
            System.out.println("You answered correctly");
        return;
        }
        else if (counter >= 3 && correct < 3) {
            System.out.println("Youve been missing the questions lately, let me help! ");
        }
        else
        {
            System.out.println("Try again");
            counter++;
            correct = 0;
        break;
            }
        }
    }
}

I expect the program to output correct answers out of attempts after the user completes 3 problems in a row. 我希望程序在用户连续完成3个问题后能输出正确的答案。 In addition, it needs to output a tip after 3 attempts. 另外,它需要在3次尝试后输出一个提示。 And then after 3 correct, it should loop back to the beginning of program. 然后在3正确之后,它应该循环回到程序的开头。

It's quite late on a saturday for me to do algebra, so I will stick to suggesting changes to the structure of your program. 对我来说,星期六进行代数已经很晚了,所以我将坚持建议对程序结构进行更改。 First, you can accomplish everything with a single class to contain the questions, and score for the user. 首先,您可以使用一个类完成所有问题,以包含问题并为用户评分。 The methods in that class can be chosen via a menu in the main. 可以通过主菜单选择该类中的方法。 I wrote a sample of how I would structure this based on standard Java OOP methodology. 我写了一个示例,说明如何基于标准Java OOP方法构建此结构。 In my program, the main needs no static class, it loops a menu, and the choice of a question is made there. 在我的程序中,main不需要静态类,它循环了一个菜单,并在那里选择了一个问题。 My methods hava single question, you can add as many as you like in the menu, the important thing is the structure. 我的方法有一个问题,您可以在菜单中添加任意多个,重要的是结构。

 import java.util.Scanner;

//This class contains the two methods and over-all score
class Material {
private int score;
//The user chooses this or the earth method
public void sky() {

    String answer = "null"; 
    int count = 0;
    Scanner input = new Scanner(System.in);
   //within the method, is this while loop which gives a hint after 3 attempts.
    while (!answer.equals("blue") && (!answer.equals("exit"))) {
        System.out.println("What color is the sky? 'exit' to exit");
        answer = input.nextLine();
        count++;
        if (count == 3)
            System.out.println("Hint: It starts with a 'b'");
    }

    if (answer.equals("blue"))
        score += 1;//The score will increment if the choice is correct,
    else//or else leave with nothing...
        return;
}

    //This method is the same as the sky() method, just different question and answer.
public void earth() {

    String answer = "null";
    int count = 0;
    Scanner input = new Scanner(System.in);

    while (!answer.equals("iron") && (!answer.equals("exit"))) {
        System.out.println("What is the core made of? 'exit' to exit");
        answer = input.nextLine();
        count++;
        if (count == 3)
            System.out.println("Hint: It starts with a 'i'");
    }

    if (answer.equals("iron"))
        score += 1;
    else
        return;

}

public int getScore() {
    return score;
}

}

public class Questions {

public static void main(String[] args) {
    //No static methods needed, here is an instance of our test materia class.
    Material material = new Material();

    //The choice and scanner are instantiated here.
    int choice = 0;
    Scanner input = new Scanner(System.in);

    //This while loop uses a switch statement to choose the methods for the questions
    while (choice != 3) {

        if (material.getScore() == 3) {
            System.out.println("Good job, you scored three right.");
            return;
        }

        System.out.println("SCORE: " + material.getScore());
        System.out.println("Anwer questions about the sky: 1");
        System.out.println("Answer quetions about the earth: 2");
        System.out.println("Exit: 3");
        choice = input.nextInt();
       //choices are 1 , 2 for questions, and 3 to leave.
        switch (choice) {
        case 1:
            material.sky();
            break;
        case 2:
            material.earth();
            break;
        case 3:
            System.out.println("Exiting...");
            break;
        default:
            System.out.println("not a valid number choice...");

        }
    }

}// main
}// class

well I figured I would let you figure out how to make it loop on your own but I solved your other problems and put comments where I changed things. 好吧,我想让您知道如何使它自己循环,但是我解决了您的其他问题,并在更改内容的地方添加了注释。 Hope this helps 希望这可以帮助

//declared variables here. global variables must be declared static when accessed in a static method (ex: user_input())
static int y_;
static int m_;
static int b_;
static int x_;

public static void main(String[] args) {
    // Creates scanner for input of menu Def as menu selector
    Scanner user_Selection = new Scanner(System.in);

    System.out.println("Enter 1 if you would like to solve for Y?");
    System.out.println("Enter 2 if you would like to solve for M?");
    System.out.println("Enter 3 if you would like to solve for B?");
    System.out.println("Enter 4 to Quit");

    //Converts user input to an integer
    int selection = user_Selection.nextInt();

    //call user_input()
    user_input(selection);


}

public static void user_input(int selection) {

    Scanner user_Selection = new Scanner(System.in);
    int userAnswer;
    int y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
    int slope = (int) Math.floor(Math.random() * 201) - 100;
    int point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
    int independent_variable = (int) Math.floor(Math.random() * 201) - 100;

    y_ = point_of_line_cross;
    m_ = slope;
    b_ = y_intercept;
    x_ = independent_variable;


    //Tests what user input was, with expected output
    if (selection == (1)) {
        System.out.println("You chose to solve for Y: ");
        System.out.println("Y = " + slope + "(" + independent_variable + ")" + " + " + y_intercept);
        System.out.println("Input your answer: ");
        userAnswer = user_Selection.nextInt();
        /*After user enters answer we test the answer by calling test_input
         * */
       test_input(userAnswer);
    } else if (selection == (2)) {
        System.out.println("You chose to solve for M: ");
        System.out.println("M = " + "(" + point_of_line_cross + " - " + y_intercept + ")" + " / " + independent_variable);
        System.out.println("Input your answer: ");
        userAnswer = user_Selection.nextInt();
        /*After user enters answer we test the answer by calling test_input
         * */
        test_input(userAnswer);
    } else if (selection == (3)) {
        System.out.println("You chose to solve for B: ");
        System.out.println("B = " + point_of_line_cross + " - " + slope + "(" + independent_variable + ")");
        System.out.println("Input your answer: ");
        userAnswer = user_Selection.nextInt();
        /*After user enters answer we test the answer by calling test_input
         * */
        test_input(userAnswer);
    } else if (selection == (4)) {
        System.out.println("You chose to quit the program. ");
    }
}

// you forgot to include return type ex: void, int, String, double, float, etc
public static void test_input(int entered_answer) {
    //Solves the problem in order to compare to User input
    int answer_y = ((m_) * (x_)) + (b_);
    int answer_m = (y_) - ((b_) / (x_));
    int answer_b = (y_) - ((m_) * (x_));

    //Problem solver defined
    int answer = entered_answer;

    //Creates loop for program
    int counter = 0;
    int correct = 0;
    boolean answers_correct = false;

    while (!answers_correct && correct < 3) {
        if (answer == answer_y) {
            counter++;
            correct++;
            System.out.println("You answered correctly");
            return;
        } else if (counter >= 3 && correct < 3) {
            System.out.println("You've been missing the questions lately, let me help! ");
        } else {
            System.out.println("Try again");
            counter++;
            correct = 0;
            break;
        }
    }

}

` `

public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable)

If you give a method parameters, then when the method is called you will have to enter the values into the parameter yourself. 如果为方法提供参数,则在调用方法时,您必须自己将值输入参数中。 I don't think this is what you intended because you defined what you wanted those parameter values to be here: 我认为这不是您想要的,因为您定义了想要这些参数值位于此处的内容:

y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;

In your test_input() method you wrote: 在您的test_input()方法中,您编写了:

Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();

.nextInt() will make the program halt and wait for user input so you don't want to use it until you are ready to get the input. .nextInt()将使程序暂停并等待用户输入,因此在准备好获取输入之前,您不希望使用它。

I don't really know much about the var keyword in java but rather than using var I figured you should just declare the variable type so from this: 我对Java中的var关键字并不是很了解,但是我认为应该只声明变量类型,而不是使用var:

var counter = 0;

to this: 对此:

int counter = 0;

and to get a better understanding on how methods work I recommend these two videos: Intro to java methods Java method parameters and return types 为了更好地理解方法的工作原理,我推荐以下两个视频: Java方法 简介 Java方法参数和返回类型

For an in depth explanation of the fundamentals of java in general then I recommend this whole playlist Java Beginner Programming 对于一般的Java基础的深入解释,那么我推荐整个播放列表Java初学者编程

Side note: instead of asking the user for 1, 2, 3 or 4, you should directly ask them to enter the variable they want to solve: 旁注:而不是要求用户输入1、2、3或4,您应该直接要求他们输入要解决的变量:

Solve the equation y = m * x + b for which variable (y, m, b, quit)? 求解方程y = m * x + b,其中哪个变量(y,m,b,退出)?

This makes the users of the program think more in the problem domain instead of some technically useless indirection. 这使程序的用户在问题域中思考更多,而不是在技术上无用的间接。


As you have a Python background you should know that the indentation of the lines is important and has meaning. 由于具有Python背景,因此您应该知道这些行的缩进非常重要并且具有一定的意义。 It's the same for Java programs. Java程序也是如此。 The only difference is that the Java compiler ignores the indentation completely. 唯一的区别是Java编译器完全忽略了缩进。 But Java programs are also read by humans, and for them the indentation is viable for understanding the structure of the program. 但是Java程序也会被人类阅读,对于他们来说,缩进对于理解程序的结构是可行的。 The code you posted has inconsistent indentation, and you should let your IDE fix that. 您发布的代码的缩进不一致,您应该让您的IDE对此进行修复。


Your program should be structured like this: 您的程序的结构应如下所示:

public class AlgebraTutor {

    private final Scanner in = new Scanner(System.in);
    private final PrintStream out = System.out;

    private int attempts = 0;

    void solveForY() {
        ...
    }

    void solveForM() {
        ...
    }

    void solveForB() {
        ...
    }

    void mainMenu() {
        while (true) {
            out.println("Solve the equation y = m * x + b for which variable (y, m, b), or quit?");
            if (!in.hasNextLine()) {
                return;
            }

            switch (in.nextLine()) {
            case "y":
                solveForY();
                break;

            case "m":
                solveForX();
                break;

            case "b":
                solveForB();
                break;

            case "q":
            case "quit":
                return;
            }
        }
    }

    public static void main(String[] args) {
        new AlgebraTutor().mainLoop();
    }
}

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

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