Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

How to fix NullPointerException in Java?

I'm creating a math program that asks the user how many digits they'd like to use, then asks them what kind of math they want to do. It then asks the user 10 math questions based on their answers. It then decides if they're right or wrong and displays an appropriate message. It then calculates their percentage of correct answers and displays a message based on the percentage.

I seem to have the math logic working, but as soon it loops into the second question, I get a NullpointerException.

I've never run into this issue before, but what I gathered from searching around is that it means that I'm trying to use an object that has a null value (not 100% on this?). Can anyone tell me why this code would work fine the first time around, but then throw this exception the second time around?

Thanks for any help.

Exception in thread "main" java.lang.NullPointerException at assignment2.Assignment2.askQuestion(Assignment2.java:104) at assignment2.Assignment2.main(Assignment2.java:43)

Line 104 reads

operatorText = (selectedOperator == 5) ? operators[(int) Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];

Line 43 reads

   askQuestion(0, null, 0, 0, null, 0);

Full code

import java.util.*;
import javax.swing.JOptionPane;

public class Problem2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        int difficulty = 1;
        String[] operators = {"plus", "minus", "times", "divided by"};
        int selectedOperator = 1;
        int correctAnswers = 0;
        int answeredTyped = 0;

        int difficultyInput = Integer.parseInt(
            JOptionPane.showInputDialog("Please choose the difficulty. " +
                    "Enter the number of digits to use in each problem."));

        if (difficultyInput > 0) {
            difficulty = difficultyInput;
        }
        int arithmeticMethod = Integer.parseInt(
            JOptionPane.showInputDialog(
                "Choose an arithmetic problem to study: 1 " +
                "= Addition Only, 2 = Subtraction Only, 3 = " +
                "Multiplication Only, 4 = Division Only, 5 = Random Problems" ));

        selectedOperator = arithmeticMethod;

        new Problem2().askQuestion(difficulty, null,
                    arithmeticMethod, arithmeticMethod,
                                operators, arithmeticMethod);

        while(answeredTyped < 10) {
            askQuestion(0, null, 0, 0, null, 0);
            if(((float)correctAnswers / answeredTyped) >= 0.75) {
                JOptionPane.showMessageDialog(null,
                    "Congratulations, you are ready to go on to the next level!");
            } else {
                JOptionPane.showMessageDialog(
                    null, "Please ask your teacher for extra help.");
            }
        }
    }

    public static boolean checkResponse (double primaryInt,
            double secondaryInt, String operatorText, double response){
        if (operatorText.equals("plus")) {
            return (primaryInt + secondaryInt) == response;
        } else if (operatorText.equals("minus")) {
            return (primaryInt - secondaryInt) == response;
        } else if (operatorText.equals("times")) {
            return (primaryInt * secondaryInt) == response;
        } else if (operatorText.equals("divided by")) {
            return (primaryInt / secondaryInt) == response;
        }
        return false;
    }

    public static String displayResponse (boolean isCorrect) {
        int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
        switch (randomIndex) {
            case 1:
                return isCorrect ? "Very Good!" : "No. Please try again.";
            case 2:
                return isCorrect ? "Excellent!" : "Wrong. Try once more.";
            case 3:
                return isCorrect ? "Nice Work!" : "Don't give up!";
            case 4:
                return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
        }
        return "Oops...";
    }

    public static void askQuestion(int difficulty,
            String operatorText, int selectedOperator,
                int answeredTyped, String[] operators, int correctAnswers){
        boolean correctAnswer = false;
        double primaryInt = Math.floor(Math.pow(10,
            difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
        double secondaryInt = Math.floor(Math.pow(10,
            difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
        operatorText = (selectedOperator == 5) ? operators[(int) Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];

        while(!correctAnswer && answeredTyped < 10) {
            double response = Double.parseDouble (
                JOptionPane.showInputDialog("How much is " +
                    primaryInt + " " + operatorText + " " + secondaryInt + "?"));
            correctAnswer = checkResponse (primaryInt,
                    secondaryInt, operatorText, response);
            JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));

            answeredTyped++;

            if(correctAnswer)
                correctAnswers++;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

askQuestion(0, null, 0, 0, null, 0);

All the parms to the static method askQuestion are null/zero, including "operators". There's no way for "operators" to NOT be null when you get to that squirrely assignment to "operatorText".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...