if语句

时间:2016-09-11 15:41:35

标签: java

在这个代码块中,在第十三行,我将correctAnswers增加1.然而,一旦if语句中断,当打印百分比时,该值只是一个(或有时为零)。谁能告诉我我的代码有什么问题?

private static void multiplicationTest(int maxNumber, int minNumber) {  
    int i = 1;                                                          

    while(i != 11) {                                                    
        int firstNumber = (minNumber + (int)(Math.random() * ((maxNumber - minNumber) + 1)) ), secondNumber = (minNumber + (int)(Math.random() * ((maxNumber - minNumber) + 1)) );
        int inputAnswer, answer = (firstNumber * secondNumber);
        int correctAnswers = 0;

        System.out.print("Question " + i + ".)\t" + firstNumber + " * " + secondNumber + " = ");
        inputAnswer = input.nextInt();

        if(inputAnswer == answer) {
            correctAnswers++;
            System.out.print("\tcorrect\n");

        } else {
            System.out.print("\tincorrect --- " + firstNumber + " * " + secondNumber + " = " + answer + "\n");

        } if(i == 10) {
            System.out.println("\nYou scored " + correctAnswers + " out of 10 - " + (correctAnswers * 10) + "%.");

        }

        i++;
    }

}

2 个答案:

答案 0 :(得分:2)

int correctAnswers = 0;放在while行之前。

如果它在while循环中,它将在每次运行时保持重置总分。

这意味着每次得分真的不合格,而不是10分。

答案 1 :(得分:0)

UserF40指出了您的错误。其余的,我会做一个简短的代码审查。

  1. 您正在使用func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey .sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } 循环从1到10进行计数。使用while循环来执行此操作要简单得多:for。当存在非数字布尔条件时,使用for (int i = 1; i < 11; ++i)循环来终止循环。

  2. 您的第二个while放错了地方,可以省略。由于它只对最后一次循环进行操作,因此您可以在循环终止后执行操作,而不需要if

  3. 学习Java库。你if对实数有好处,但对整数不好。对于随机整数,使用直接提供整数的Math.random()

  4. 避免在一行上进行多次声明,这是不必要的,可能会造成混淆。每行一个声明更清晰。