জাভা প্রোগ্রামিং পর্ব-২০



Problem: An Improved Math Learning Tool
Suppose you want to develop a program for a first-grader to practice subtraction. The program randomly generates two single-digit integers, number1 and number2, with number1 > = number2 and displays to the student a question such as “What is 9-2? ” After the student enters the answer, the program displays a message indicating whether it is correct. The previous programs generate random numbers using System.currentTimeMillis(). A better approach is to use the random() method in the Math class. Invoking this method returns a random double value d such 0.0 <= d <1.0 that So, (int)(Math.random() * 10) returns a random single-digit integer (i.e., a number between 0 and 9). The program may work as follows:

Generate two single-digit integers into number1 and number2.
If number1 < number2, swap number1 with number2.
Prompt the student to answer “What is number1 – number2?”
Check the student’s answer and display whether the answer is correct.

File name : SubtractionQuiz.java

import java.util.Scanner;
public class SubtractionQuiz {
  public static void main(String[] args) {
    // 1. Generate two random single-digit integers
    int number1 = (int)(Math.random() * 10);
    int number2 = (int)(Math.random() * 10);

    // 2. If number1 < number2, swap number1 with number2
    if (number1 < number2) {
      int temp = number1;
      number1 = number2;
      number2 = temp;
    }

    // 3. Prompt the student to answer “what is number1 – number2?”
    System.out.print
      ("What is " + number1 + " - " + number2 + "? ");
    Scanner input = new Scanner(System.in);
    int answer = input.nextInt();

    // 4. Grade the answer and display the result
    if (number1 - number2 == answer)
      System.out.println("You are correct!");
    else
      System.out.println("Your answer is wrong.\n" + number1 + " - "
        + number2 + " should be " + (number1 - number2));
  }
}

Loading
Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Flying Twitter Bird Widget By ICT Sparkle