想想java第3章练习3-4 - 猜猜我的号码

时间:2017-06-28 16:46:30

标签: java debugging

嘿伙计们,我正在从Think java教科书中学习一些练习。我正在第4章练习3-4,我完成了代码编写工作,但是当我在前几次运行它时它会起作用,但是当我再次尝试运行它时,会打印生成的数字而不是猜测的数字。

import java.util.Random;
import java.util.Scanner;

public class GuessMyNumber {
    //exercise 3-4
    public static void main (String[]args) {
        //pick a number
        int numberGuessed;
        int numberGenerated;
        int difference;

        //generate a random number
        Random random = new Random();
        numberGenerated = random.nextInt(100) + 1;
        Scanner sc = new Scanner(System.in);

        //prompt for user input
        System.out.println("Im Thinking of a Number between 1 and 100 \nCan you Guess what it is? ");
        System.out.print("Type a Number: ");
        numberGuessed = sc.nextInt();
        System.out.println("Your Guess is: " + numberGuessed);
        System.out.println("The Number I was Thinking of is: " + numberGenerated);

        //modulation operator
        difference = numberGenerated % numberGuessed;
        System.out.println(difference);
        System.out.printf("you were of by: %d", difference);
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你困惑的是模运算。至少文本不适合它正在做的事情。要计算你要做的两个数字之间的差异

difference = numberGenerated - numberGuessed;

如果您不想使用负值,可以使用

difference = java.lang.Math.abs(numberGenerated - numberGuessed);

模运算符为您提供其余的除法。