dimanche 24 avril 2016

Subtracting Random numbers

I'm making a game where the user must solve a simple subtraction but the result must be a positive whole number. I managed to do everything but for some reason the answer is sometimes negative and I'm not sure how to fix it

import java.util.Random;
import java.util.Scanner;
public class Subtraction {
  public static void main(String[] args) {
    Random r = new Random();

    final int MAX = 10;
    // get two random numbers between 1 and MAX
    int num1 = r.nextInt(MAX) - 1;
    int num2 = r.nextInt(MAX) - 1;

    int total = (num1 - num2);

    // display a question
    System.out.printf("What is your answer to %d - %d = ?%n", num1, num2);

    // read in the result
    Scanner stdin = new Scanner(System.in);
    int ans = stdin.nextInt();
    stdin.nextLine();

    // give an reply
    if (ans == total) {
      System.out.println("You are correct!");
    } else {
      System.out.println("Sorry, wrong answer!");
      System.out.printf("The answer is %d + %d = %d%n", num1, num2, (num1 - num2));
    }

  }
}




Aucun commentaire:

Enregistrer un commentaire