View Single Post
 01-03-2013, 06:25 AM PM User | #1 comfroels New Coder   Join Date: Jan 2012 Posts: 13 Thanks: 0 Thanked 0 Times in 0 Posts Random Number Generator Methods Question Hello Everyone, I'm still pretty new to java and still learning but created a little console program to test you on how well you can calculate change. It functions (not perfectly) but I know there are better ways to do what I did. Any suggestions to help me develop better technique? Also, I thought I could use methods different times and have it return a different value. As you will see I had to make two different random number generators. Then since they were both currentTimeMillis() they were still returning the same values, so i switch one to nanoTime(). Here's the code Code: ```import java.util.Scanner; import java.util.Random; public class ChangeTest { public static void main(String[] args) { double number1 = 0.0; double number2 = 0.0; int numCorrect = 0; double answer = 0.0; double userAnswer = 0.0; for(int i = 1; i <= 10;++i){ Scanner input = new Scanner(System.in); number1 = (double)Math.round(genNumber1()*100)/100; number2 = (double)Math.round(genNumber2()*100)/100; if (number1 > number2){ answer = number1 - number2; System.out.println("What would be the change if the price was: \$" + number2 + " and you were given: \$" + number1); userAnswer = input.nextDouble(); if (userAnswer == answer){ ++numCorrect; System.out.println("That is correct!"); } else System.out.println("I'm sorry that is incorrect."); } else { answer = number2 - number1; System.out.printf("What would be the change if the price was: \$" + number1 + " and you were given: \$" + number2); userAnswer = input.nextDouble(); if (userAnswer == answer){ numCorrect++; System.out.println("That is correct!"); } else System.out.println("I'm sorry that is incorrect."); } } if(numCorrect == 10){ System.out.println("Congratulations! You got a perfect score!!!"); } else if (numCorrect >= 7) { System.out.println("Good work! You got " + numCorrect + " correct!!!"); } else { System.out.println("You can do better! You got " + numCorrect + " correct..."); } } static double genNumber1(){ double num1; Random generator = new Random(System.currentTimeMillis()); num1 = generator.nextDouble() * 50.0; return num1; } static double genNumber2(){ double num1; Random generator = new Random(System.nanoTime()); num1 = generator.nextDouble() * 50.0; return num1; } }``` So yeah, is there an easier way?