I'm writing a program that is a quiz where the numbers in the problem are randomized. Then the user uses the random numbers to find the answer. They get a point each time they get a problem right. I keep getting outrageous decimals when the random numbers are generated. Here's the code:
import java.util.Scanner;
public class TriviaLab
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to the Trivia Game!");
System.out.println("Please pick a category:");
System.out.println("(Input 1 for Math or 2 for Geography)");
String selection = kb.nextLine();
if ( selection.equals("1") )
{
int counter = 0;
System.out.println("Math Selected!\n");
System.out.println("Question 1");
//this is where the problem is: the doubles distance1 and time1 give me crazy huge decimals
double distance1 = Math.random() * 5;
double time1 = Math.random() * 5;
double answer1 = distance1 / time1;
double roundedanswer1 = Math.round(answer1 * 100.0) / 100.0;
System.out.println("What is the magnitude of the average speed if you travel " + distance1 + " meters in " + time1 + " seconds?");
String aM1 = kb.nextLine();
if (aM1.equals(roundedanswer1) )
{
System.out.println("Correct!");
counter = counter + 1;
System.out.println("Score=" + counter + "\n");
}
else
{
System.out.println("Incorrect!");
System.out.println("The correct answer is " + answer1);
System.out.println("Score=" + counter + "\n");
}
Aucun commentaire:
Enregistrer un commentaire