Exercise: Write a program that prints two random integers (smaller than 100 and bigger than
0). The program should ask the user to multiply the numbers and read the result
from the user. If the user has done the multiplication correctly, then the program
should print “Congratulations!” Otherwise, the program should print “Better luck
next time.”
I decided to make the exercise a little more complicated by having it ask 10 questions and then print a score at the end. Instead of the Math.random() that the book used in the chapter I decided to go with Random().
import java.util.*;
public class Multiplication{
public static void main(String[] args) {
Random randomGenerator = new Random();
int x = 1;
int y = 1;
int answer = 1;
int score = 0;
Scanner keyboard = new Scanner(System.in);
for (int a = 1; a<=10; a++){//do this 10 times
x = randomGenerator.nextInt(99)+1;//get random integer 1-99
y = randomGenerator.nextInt(99)+1;
System.out.print(x + " * " + y + " = ");//prompt user
answer = keyboard.nextInt();//get answer
if (answer == x*y){//if answer is correct
System.out.println("correct");//print correct
score++;//increase score
}
else{
System.out.println("incorrect");//print incorrect
}
}
keyboard.close();
System.out.println("Your score is "+score+"/10.");//print score
}
}

No comments:
Post a Comment