Как мне вернуться к началу моей программы после правильного ответа на вопрос 3 раза подряд / и добавить дисперсию

В Java все переменные, которые вы объявляете, на самом деле являются «ссылками» на объекты (или примитивы), а не самими объектами.

При попытке выполнить один метод объекта , ссылка просит живой объект выполнить этот метод. Но если ссылка ссылается на NULL (ничего, нуль, void, nada), то нет способа, которым метод будет выполнен. Тогда runtime сообщит вам об этом, выбросив исключение NullPointerException.

Ваша ссылка «указывает» на нуль, таким образом, «Null -> Pointer».

Объект живет в памяти виртуальной машины пространство и единственный способ доступа к нему - использовать ссылки this. Возьмем этот пример:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

И в другом месте вашего кода:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

Это важно знать - когда больше нет ссылок на объект (в пример выше, когда reference и otherReference оба указывают на null), тогда объект «недоступен». Мы не можем работать с ним, поэтому этот объект готов к сбору мусора, и в какой-то момент VM освободит память, используемую этим объектом, и выделит другую.

1
задан Pouyan Khodabakhsh 14 April 2019 в 06:43
поделиться

3 ответа

В субботу я уже слишком поздно занимаюсь алгеброй, поэтому я буду придерживаться предложения об изменении структуры вашей программы. Во-первых, вы можете выполнить все с помощью одного класса, содержащего вопросы и оценки для пользователя. Методы в этом классе могут быть выбраны через главное меню. Я написал пример того, как я буду структурировать это на основе стандартной методологии ООП Java. В моей программе основному классу не нужен статический класс, он зацикливает меню, и там делается выбор вопроса. Мои методы имеют один вопрос, вы можете добавить столько, сколько захотите, в меню, важна структура.

 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
0
ответ дан MGT 14 April 2019 в 06:43
поделиться

Я подумал, что позволю вам разобраться, как сделать это самостоятельно, но я решил другие ваши проблемы и оставил комментарии, где я что-то изменил. Надеюсь, это поможет

//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)

Если вы дадите параметры метода, то при вызове метода вам придется самостоятельно вводить значения в параметр. Я не думаю, что это то, что вы намеревались, потому что вы определили, что вы хотели, чтобы значения этих параметров были здесь:

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;

В вашем методе test_input () вы написали:

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

.nextInt () заставит программу остановиться и ждать ввода пользователя, поэтому вы не захотите использовать его, пока не будете готовы получить ввод.

Я не очень много знаю о ключевом слове var в java, но вместо того, чтобы использовать var, я решил, что нужно просто объявить тип переменной так:

var counter = 0;

так:

[ 115]

и чтобы лучше понять, как работают методы, я рекомендую эти два видео: Введение в java-методы Параметры метода Java и возвращаемые типы

Для подробное объяснение основ java в целом, тогда я рекомендую весь этот плейлист Java Beginner Programming

0
ответ дан user2626734 14 April 2019 в 06:43
поделиться

Примечание стороны: вместо того, чтобы просить у пользователя 1, 2, 3 или 4, необходимо непосредственно попросить, чтобы они ввели переменную, которую они хотят решить:

Решают уравнение y = m * x + b, для которой переменной (y, m, b, выходят)?

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

<час>

, Поскольку у Вас есть фон Python, необходимо знать, что добавление отступа строк важно и имеет значение. Это - то же для программ Java. Единственная разница - то, что компилятор Java игнорирует добавление отступа полностью. Но программы Java также прочитаны людьми, и для них, добавление отступа жизнеспособно для понимания структуры программы. Код, который Вы отправили, имеет непоследовательное добавление отступа, и необходимо позволить IDE зафиксировать это.

<час>

Ваша программа должна быть структурирована как это:

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();
    }
}
0
ответ дан Roland Illig 14 April 2019 в 16:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: