简体   繁体   English

教孩子简单加减法的Java程序

[英]Java program that teaches kid simple addition and subtraction

I feel like I'm almost there with the code but the problem is the while loop I am not allowed to use break and continue statements for this program.我觉得代码差不多了,但问题是 while 循环我不允许在这个程序中使用 break 和 continue 语句。 The first output test its suppose to have 14 questions where you get 12 right and 2 wrong giving you 86%.第一个输出测试它假设有 14 个问题,你得到 12 对和 2 错给你 86%。 As for the second test you get a perfect score while the last test takes you to 20 questions that being the max number of questions, 4 of the first 8 questions correctly and 4 of the first 8 incorrectly, and then the next 12 correctly giving you 80% Code below:至于第二次考试,你会得到满分,而最后一次考试会带你做 20 道题,这是最大问题数,前 8 题中有 4 题正确,前 8 题中有 4 题不正确,然后接下来的 12 题正确给你80% 代码如下:

package proj3;

    import java.util.Scanner;
    
    public class Project4App {
        
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            int correctNum = 0;
            int wrongNum = 0;
            double percent = 0;
            int subNumCorrect = 0;
            int subNumWrong = 0;
            int addNumCorrect = 0;
            int addNumWrong = 0;
            int totalQuestions = 0;
            
            
            while(!(correctNum == 10 && totalQuestions == 10) && !(percent >= 85.0 && totalQuestions >= 10) && (totalQuestions != 20)) {
                Question Quest = new Question();
                
                System.out.println("What is the result?" + "\n" + Quest.toString());
                int userInt = scnr.nextInt();
                
                if((Quest.getOperator() == '+') && (userInt == Quest.determineAnswer())) {
                    addNumCorrect += 1;
                }
                else if(Quest.getOperator() == '+' && (userInt != Quest.determineAnswer())) {
                     addNumWrong += 1;
                }
                
                if((Quest.getOperator() == '-') && (userInt == Quest.determineAnswer())) {
                    subNumCorrect += 1;
                }
                else if((Quest.getOperator() == '-') && (userInt != Quest.determineAnswer())) {
                     subNumWrong += 1;
                }
                   
                if(userInt == Quest.determineAnswer()){
                    correctNum += 1;
                    System.out.println("Congratulations, you got it correct!");
                }
                else if (userInt != Quest.determineAnswer()){
                    wrongNum += 1;
                    System.out.println("The correct answer for " + Quest.toString() + " is " + Quest.determineAnswer());
                }
                
                totalQuestions++;
                
                percent = Math.round((double)(correctNum * 100) / (totalQuestions));
                }
                
                System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
                System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
                System.out.println("The percent correct: " + percent + "%");
                
                
                scnr.close();
            }
        }

I think this largely does what you want.我认为这在很大程度上可以满足您的需求。 A number of the counters weren't being modified as was intended.许多计数器没有按预期进行修改。 This is partly due to the amount going on in your main method making it hard to see what's going on (too much information).这部分是由于您的主要方法中发生的数量使得很难看到发生了什么(信息太多)。 I've extracted functionality to smaller, more well defined methods.我已经将功能提取到更小、更明确的方法中。

You had a whole lot of logic effectively saying you want the user to have achieved 85% with at least 10 questions answered - and stop when 20 questions are asked.你有很多逻辑有效地说你希望用户在回答至少 10 个问题时达到 85% - 并在提出 20 个问题时停止。 You could factor this condition out to a method returning a boolean isGameComplete(totalQuestions) and put this in the while condition-expression.您可以将此条件isGameComplete(totalQuestions)为返回boolean isGameComplete(totalQuestions) ,并将其放入while条件表达式中。

I've taken the liberty of implementing a question class based on the functionality that I think achieves the intention.我冒昧地根据我认为实现意图的功能实现了一个问题类。

The correctPercent was rounded to an int which made it impossible to be == to 85.5%, say. correctPercent被四舍五入为整数,这使得 == 不可能达到 85.5%。 I've converted this to a double so if you get more than 85% , say 85.25% , the game completes successfully.我已将其转换为double因此如果您获得超过85% ,例如85.25% ,则游戏成功完成。

Probably some other stuff I've added, which I've tried to comment in-line, if significant.可能我已经添加了一些其他的东西,如果重要的话,我已经尝试在线评论。 Hopefully this is what you were after.希望这就是你所追求的。

If it ever gets too difficult to understand, extracting small chunks of code to well named methods (even long ones) helps enormously, since it reduces your mental load.如果它变得太难理解,将小块代码提取到命名良好的方法(甚至是长的)中会大有帮助,因为它可以减轻您的心理负担。

class Project4App {

    static final Scanner scanner = new Scanner(System.in);
    static int correctNum = 0;
    static int wrongNum = 0;
    static int subNumCorrect = 0;
    static int subNumWrong = 0;
    static int addNumCorrect = 0;
    static int addNumWrong = 0;
    static int totalQuestions = 0;
    static double percentCorrect = 0;

    public static void main(String[] args) {
        /**
         * answer at least 9/10 questions correctly (to get 85%)
         */
        while (percentCorrect < 85.0 && totalQuestions >= 10 && totalQuestions <= 20) {
            Question question = new Question();

            int userInt = getUsersAnswer(question);
            boolean isCorrect = question.determineAnswer(userInt);
            updateStatistics(question, isCorrect);
            printResults(); // can remove this/comment this out - added to help with debugging
        }

        System.out.println();
        System.out.println("------------ Game Complete! ------------");
        printResults();
    }

    private static void printResults() {
        System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
        System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
        System.out.println("The percent correct: (" + (addNumCorrect+subNumCorrect) + "/" + totalQuestions +") " + percentCorrect + "%");
        System.out.println("The percent wrong: (" + (addNumWrong+subNumWrong) + "/" + totalQuestions +") " + (100 - percentCorrect) + "%");
    }

    private static int getUsersAnswer(Question question) {
        System.out.println("What is the result?" + "\n" + question.toString());
        int userInt = scanner.nextInt();
        return userInt;
    }

    public static void updateStatistics(Question question, boolean isCorrect){
        if (question.getOperator() == '+') {
            if (isCorrect) {
                addNumCorrect++;
                correctNum++; // newly added (wasn't updated)
            } else {
                addNumWrong++;
                wrongNum++; // newly added - unused variable originall
            }
        } else { // operator is '-'
            if (isCorrect) {
                subNumCorrect++;
                correctNum++; // newly added (wasn't updated)
            } else {
                subNumWrong++;
                wrongNum++; // newly added - unused variable originall
            }
        }
        totalQuestions++; // newly added
        percentCorrect = (correctNum * 100) / totalQuestions;
    }
}

class Question {

    private static final int UPPER_LIMIT_ON_RANDOM_NUMBERS = 20;
    private static final Random random = new Random();
    private final int number1;
    private final int number2;
    private final char operator;

    public Question() {
        operator = Math.random()>0.5 ? '+' : '-';
        number1 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // NOTE THE SUBTRACTION NUMBER COULD BE NEGATIVE IF number2
        number2 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // IS GREATER THAN number1.
    }

    public char getOperator() {
        return operator;
    }

    public boolean determineAnswer(int userAnswer) {
        switch (operator) {
            case '+':
                return userAnswer == (number1 + number2);
            case '-':
                return userAnswer == (number1 - number2);
        }
        return false; // shouldn't end up here - would be better to throw an unchecked exception and crash the program - new RuntimeException()
    }

    @Override
    public String toString() {
        return number1 + " " + operator + " " + number2;
    }
}

Output:输出:

------------ Game Complete! ------------

Progress Report: 
Addition:
You got 7 correct and 0 incorrect.
Progress Report: 
Subtraction:
You got 2 correct and 1 incorrect.
The percent correct: (9/10) 90.0%
The percent wrong: (1/10) 10.0%

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

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