I have to write a program for my Intro to CS class as a project. The program must
ask the user for a min value (can be negative)
ask the user for a max value (also may be negative, must be greater than min though)
produce twenty random numbers that are in between the min/max values given by the user and
produce an average of the twenty random numbers produced.
I thought I had completed the program but the numbers are never random when I execute the program, all twenty numbers come out to be the same value as the max value I enter into emacs. And of course the average is the same as the max value in this case as well. This is my program so far...
import java.util.Scanner;
import java.util.Random;
public class CS_ProjectOne
{
public static void main(String[] args)
{
int minimum_integer;
int maximum_integer;
int rn1;
int rn2;
int rn3;
int rn4;
int rn5;
int rn6;
int rn7;
int rn8;
int rn9;
int rn10;
int rn11;
int rn12;
int rn13;
int rn14;
int rn15;
int rn16;
int rn17;
int rn18;
int rn19;
int rn20;
double total;
double average;
Scanner keeper;
Scanner keeper2;
Random gen;
gen = new Random();
keeper = new Scanner(System.in);
System.out.print("Please enter an integer for the MINIMUM value: ");
minimum_integer = keeper.nextInt();
keeper2 = new Scanner(System.in);
System.out.print("Please enter an integer for the MAXIMUM value: ");
maximum_integer = keeper2.nextInt();
rn1 = gen.nextInt();
rn1 = rn1 % minimum_integer + maximum_integer;
rn2 = gen.nextInt();
rn2 = rn2 % minimum_integer + maximum_integer;
rn3 = gen.nextInt();
rn3 = rn3 % minimum_integer + maximum_integer;
rn4 = gen.nextInt();
rn4 = rn4 % minimum_integer + maximum_integer;
rn5 = gen.nextInt();
rn5 = rn5 % minimum_integer + maximum_integer;
rn6 = gen.nextInt();
rn6 = rn6 % minimum_integer + maximum_integer;
rn7 = gen.nextInt();
rn7 = rn7 % minimum_integer + maximum_integer;
rn8 = gen.nextInt();
rn8 = rn8 % minimum_integer + maximum_integer;
rn9 = gen.nextInt();
rn9 = rn9 % minimum_integer + maximum_integer;
rn10 = gen.nextInt();
rn10 = rn10 % minimum_integer + maximum_integer;
rn11 = gen.nextInt();
rn11 = rn11 % minimum_integer + maximum_integer;
rn12 = gen.nextInt();
rn12 = rn12 % minimum_integer + maximum_integer;
rn13 = gen.nextInt();
rn13 = rn13 % minimum_integer + maximum_integer;
rn14 = gen.nextInt();
rn14 = rn14 % minimum_integer + maximum_integer;
rn15 = gen.nextInt();
rn15 = rn15 % minimum_integer + maximum_integer;
rn16 = gen.nextInt();
rn16 = rn16 % minimum_integer + maximum_integer;
rn17 = gen.nextInt();
rn17 = rn17 % minimum_integer + maximum_integer;
rn18 = gen.nextInt();
rn18 = rn18 % minimum_integer + maximum_integer;
rn19 = gen.nextInt();
rn19 = rn19 % minimum_integer + maximum_integer;
rn20 = gen.nextInt();
rn20 = rn20 % minimum_integer + maximum_integer;
System.out.println("Your random numbers are: " + rn1 + ", " + rn2 + ", " + rn3 + ", " + rn4 + ", " + rn5 + ", " + rn6 + ", " + rn7 + ", " + rn8 + ", " + rn9 + ", " + rn10 + ", " + rn11 + ", " + rn12 + ", " + rn13 + ", " + rn14 + ", " + rn15 + ", " + rn16 + ", " + rn17 + ", " + rn18 + ", " + rn19 + ", " + rn20 + ".");
total = rn1 + rn2 + rn3 + rn4 + rn5 + rn6 + rn7 + rn8 + rn9 + rn10 + rn11 + rn12 + rn13 + rn14 + rn15 + rn16 + rn17 + rn18 + rn19 + rn20;
average = total / 20;
System.out.print("The average is " + average);
}
}
Could anyone be of some help and steer me in the right direction? I'm sure there is something I'm not doing correctly (or many things) I just don't know what exactly that is.
Here is a shorter version of me trying to get this to work...
import java.util.Random;
import java.util.Scanner;
public class p1
{
public static void main(String[] args)
{
Random gen;
gen = new Random();
Scanner keeper;
int range, user_min, user_max, num1, num2, num3, total;
double average;
keeper = new Scanner(System.in);
System.out.print("Please enter a maximum integer value: ");
user_max = keeper.nextInt();
keeper = new Scanner(System.in);
System.out.print("Please enter a minimum integer value: ");
user_min = keeper.nextInt();
range = user_max - user_min + 1;
num1 = gen.nextInt() % range + user_min;
num2 = gen.nextInt() % range + user_min;
num3 = gen.nextInt() % range + user_min;
System.out.print("The random numbers computed are " + num1 + ", " + num2 + ", " + num3 + ", ");
}
}
Why can't this handle negatives? And my values still aren't within the specified range? HELP?
Some tips/hints:
Use an array for the 20 numbers. Then when you find a mistake, you only have to correct it once rather than 20 times.
Random number generators have seeds. Make sure that you provide a different seed each time, otherwise your random number generator will always generate the same set of random numbers.
How many values can there be between MIN and MAX? For example, how many different values can there be between 3 and 7? 45 and 80? 3 and 1200? Find the pattern.
Understand why your program needs the '%' operator. What is being achieved by doing "gen.nextInt() % NUM"?
Random List Example:
(In Python instead of Java for ease of demonstration.)
1 #!/usr/bin/env python
2 def spawn(user_min, user_max, rounds):
3 import random
4 sum = 0
5 user_range = user_max - user_min + 1
6 for i in range(rounds):
7 result = int((random.random() * user_range)) + user_min
8 sum = sum + result
9 print(str(i) + ': ' + str(result))
10 mean = sum / rounds
11 print('range: ' + str(user_range))
12 print('mean: ' + str(mean))
The lines of interest for you are:
Line 5: This determines the spread of the random number.
Line 7: This fetches a random value of range [0.0, 1.0); multiplies by the desired user range; then casts to integer to 'chop off' the trailing decimal points; and then adds the result to the minimum allowed value of the range.
For example:
range = (10) - (-5) + 1 = 16
a_result = (int)(0.14159265359 * 16) + -5 = 3 - 5 = -3
another_result = (int)(0.71828182845 * 16) + -5 = 11 - 5 = 6
The line
rn1 = rn1 % minimum_integer + maximum_integer;
is wrong. Consider for example generating numbers in the range 1 to 6. Then you are calculating
rn1 = rn1 % 1 + 6;
Now, rn1 % 1 is always equal to 0, so you always get 6. You should use a different formula.
Thats what I came up with..
import java.util.*;
class RandNegToPos {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int array[]=new int[20];
System.out.println("What is the minimum? ");
int min = scan.nextInt();
System.out.println("What is the maximum? ");
int max = scan.nextInt();
if (max < min)
System.out.println("Sorry the maximum is less than the miniumum.");
else{
int rnd = (int) (min + Math.random() * ((max) - min));
for (int i=0; i < 20 ; i++)
{
rnd = (int) (min + Math.random() * ((max) - min));
array[i] = rnd;
}
int sum=0;
for (int t : array)
sum += t;
System.out.println("Your randoms are:");
System.out.println(Arrays.toString(array));
System.out.println("The average is: " + (sum/20) );
}
}
}
Related
import java.util.Scanner;
public class MoneyChange {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Input an amount of money: ");
double value = reader.nextDouble();
int money = (int) value;
int thousand = money / 1000;
int fivehundred = money / 500;
int hundred = money / 100;
int fifty = (money % 100) / 50;
int twenty = ((money % 100) % 50) / 20;
int ten = (((money % 100) % 50) % 20) / 10;
int five = ((((money % 100) % 50) % 20) % 10) / 5;
int one = (((((money % 100) % 50) % 20) % 10) % 5) / 1;
System.out.println("Number of 1000-Bhat Banknote(s) is " + thousand);
System.out.println("Number of 500-Bhat Banknote(s) is " + fivehundred);
System.out.println("Number of 100-Bhat Banknote(s) is " + hundred);
System.out.println("Number of 50-Bhat Banknote(s) is " + fifty);
System.out.println("Number of 20-Bhat Banknote(s) is " + twenty);
System.out.println("Number of 10-Bhat Coin(s) is " + ten);
System.out.println("Number of 5-Bhat Coin(s) is " + five);
System.out.println("Number of 1-Bhat Coin(s) is " + one);
reader.close();
}
}
I would like to know how to continue the values from the first variable onto the other and not start again. Help me out!
In this code
int fifty = (money % 100) / 50;
you can calculate money % 100 and store it in a variable you can re-use it
int hun = money % 100;
int fifty = (hun) / 50;
Also be aware of Integer division
please do small modifications in your program.please take the look below code once.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Input an amount of money: ");
double value = reader.nextDouble();
int money = (int) value;
int thousand = money / 1000;
int remain = money % 1000 ;
int fivehundred = remain / 500;
remain = remain % 500;
int hundred = remain / 100;
remain = remain % 100;
int fifty = remain / 50;
remain = remain % 50;
int twenty = remain / 20;
remain = remain % 20;
int ten = remain / 10;
remain = remain % 10;
int five = remain / 5;
remain = remain % 5;
int one = remain / 1;
System.out.println("Number of 1000-Bhat Banknote(s) is " + thousand);
System.out.println("Number of 500-Bhat Banknote(s) is " + fivehundred);
System.out.println("Number of 100-Bhat Banknote(s) is " + hundred);
System.out.println("Number of 50-Bhat Banknote(s) is " + fifty);
System.out.println("Number of 20-Bhat Banknote(s) is " + twenty);
System.out.println("Number of 10-Bhat Coin(s) is " + ten);
System.out.println("Number of 5-Bhat Coin(s) is " + five);
System.out.println("Number of 1-Bhat Coin(s) is " + one);
reader.close();
}
May I know what is the argument need to sset in ()? 0 or 1? My datasets have three classes.
System.out.println("False Negative % = " + eval.falseNegativeRate(1));
System.out.println("True Negative % = " + eval.trueNegativeRate(1));
System.out.println("True Positive % = " + eval.truePositiveRate(1));
System.out.println("Accuracy % = " + accuracy);
System.out.println("Precision % = " + eval.precision(1));
System.out.println("Recall % = " + eval.recall(1));
System.out.println("F-Measure % = " + eval.fMeasure(1));
System.out.println("Error rate % = " + eval.errorRate());
I am trying to make a program where the user can input the target as well as the amount of times he wants to hit the target. The problem is that I dont know how to make the while loop run more than once (satisfy the condition more than one time).
Scanner target = new Scanner(System.in);
System.out.println("Enter dice target (1-10):");
int targetNumber = target.nextInt();
Scanner required = new Scanner(System.in);
System.out.println("Enter the number of required matches: ");
int requiredMatches = target.nextInt();
int number = (int) (1 + 10 * Math.random());
int sum = 1;
if (targetNumber > 10) {
System.out.println("Error");
}
else {
while (number != targetNumber) {
System.out.println("Your number is " + number);
number = (int) (1 + 10 * Math.random());
++sum;
}
System.out.println("You reached your target " + requiredMatches + " times in " + sum + " tries.");
}
The code lets me match the target only once, but I want it to be able to obtain the target value [RequiredMatches] times before it stops.
If the number matches, then reduce the tries by 1.
Scanner Required = new Scanner(System.in);
System.out.println("Enter the number of required matches: ");
int RequiredMatches = Target.nextInt();
int Number = (int) (1 + 10 * Math.random());
int sum = 1;
if (NumberTarget > 10) {
System.out.println("Error");
} else {
while ((Number != NumberTarget) || (RequiredMatches > 0)) {
System.out.println("Your number is " + Number);
Number = (int) (1 + 10 * Math.random());
++sum;
if (Number==NumberTarget) {
RequiredMatches--;
}
System.out.println("You reached your target " + RequiredMatches + " times in " + sum + " tries.");
}
}
I'm new to the programming world so I'd deeply appreciate if any of you could help me become better at this. My goal for this program is to simulate 3000 dice rolls and count the number of times doubles are rolled for each of the different possible pairs of doubles using a while loop. The results should be printed out in a dialog box.
Random random;
random = new Random();
diceRolls = 1;
snakeEyes = 1;
doubleTwos = 1;
doubleThrees = 1;
doubleFours = 1;
doubleFives = 1;
doubleSixes = 1;
while (diceRolls <= finalDiceRoll) {
int diceRolls = 1;
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1){
//snakeEyes = snakeEyes + 1;
snakeEyes++;
}
else if (die1 == 2 && die2 == 2 ) {
doubleTwos++;
}
else if (die1 == 3 && die2 == 3) {
doubleThrees++;
}
else if (die1 == 4 && die2 == 4) {
doubleFours++;
}
else if (die1 == 5 && die2 == 5) {
doubleFives++;
}
else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
JOptionPane.showMessageDialog (null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
}
The issue i'm having here is that the results i'm getting from the program don't seem "plausible". For example, out of 3000 dice rolls, I get 1 pair of each double. What am I doing wrong?
Few changes you have to make in your code,
1. Initialize all your variables by 0.
2. change while-loop condition to
while (diceRolls <= finalDiceRoll) // hoping that finalDiceRoll = 3000
3 remove int diceRolls = 1; from while-loop and add diceRolls++; at end of while-loop.
4. Put your JOptionPane outside while-loop. if not you have to close 3000 time your JOptionPane dailog.
After applying these changes to your code you will learn what have you done wrong and your code will run fine.
Move the showMessageDialog outside of the while loop and increment the diceRolls variable. Initialize all other integer variables with 0.
A better (cleaner and shorter) approach would be to use a two-dimensional array or a map.
Random random = new Random();
int snakeEyes = 0;
int doubleTwos = 0;
int doubleThrees = 0;
int doubleFours = 0;
int doubleFives = 0;
int doubleSixes = 0;
int diceRolls = 1;
while (diceRolls <= 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1) {
snakeEyes++;
} else if (die1 == 2 && die2 == 2) {
doubleTwos++;
} else if (die1 == 3 && die2 == 3) {
doubleThrees++;
} else if (die1 == 4 && die2 == 4) {
doubleFours++;
} else if (die1 == 5 && die2 == 5) {
doubleFives++;
} else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
diceRolls++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
The above-mentioned shorter version:
Random random = new Random();
int[] doubled = new int[6];
for (int diceRolls = 0; diceRolls < 3000; diceRolls++) {
int die1 = random.nextInt(6);
int die2 = random.nextInt(6);
if (die1 == die2)
doubled[die1]++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + doubled[0] + " times\nYou rolled double twos " + doubled[1] + " times\nYou"
+ " rolled double threes " + doubled[2] + " times\nYou rolled double fours " + doubled[3] + " times\nYou"
+ " rolled double fives " + doubled[4] + " times\nYou rolled double sixes " + doubled[5] + " times");
The counting logic should go as follows:
doubleTwos = 0;
doubleThrees = 0;
doubleFours = 0;
doubleFives = 0;
doubleSixes = 0;
finalDiceRoll = 3000;
int diceRolls = 0;
while (diceRolls < finalDiceRoll) {
++diceRolls;
With any message after the loop.
With an array you may save typing:
int[] doubleCounts = new int[6]; // By 0 based dice values
for (int i = 0; i < finalDiceRoll; ++i) {
int die1 = random.nextInt(6); // With dice values 0-5
int die2 = random.nextInt(6);
if (die1 == die2) {
++doubleCounts[die1];
}
}
int snakeEyes = doubleCounts[0];
int doubleTwos = doubleCounts[1];
...
Simplify. Eliminate duplications. Don't use multiple variables when you can use an array.
int[] doubles = new int[7]; // make the index the number rolled (ignore index 0)
int diceRolls = 0;
while (diceRolls++ < 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == die2)
doubles[die1]++;
}
String output = "";
for (int i = 1; i <= 6; i++)
output += "You rolled double " + i + "'s " + doubles[i] + " times\n";
JOptionPane.showMessageDialog (null, output);
That's all you need.
I need to modify the code so that,
its structure is better
it is more readable
it uses methods and parameters
only one statement needs to be changed if a different number of integers is to be input
My new code is at the bottom but it's not working yet, can't quite figure out what else I need to do to it. If anyone could help that would be fab.
Original Code
import java.util.Scanner;
public class MakeMeBetter
{
public static void main(String[] args)
{
int[] a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Scanner b = new Scanner(System.in);
System.out.println("Please input 10 numbers in the range 1-19 :> ");
int c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[0] = c;
int d = b.nextInt();
while (d < 1 || d > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[1] = d;
int e = b.nextInt();
while (e < 1 || e > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[2] = e;
int f = b.nextInt();
while (f < 1 || f > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[3] = f;
int g = b.nextInt();
while (g < 1 || g > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[4] = g;
int h = b.nextInt();
while (h < 1 || h > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[5] = h;
int i = b.nextInt();
while (i < 1 || i > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[6] = i;
int j = b.nextInt();
while (j < 1 || j > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[7] = j;
int k = b.nextInt();
while (k < 1 || k > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[8] = k;
int l = b.nextInt();
while (l < 1 || l > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[9] = l;
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
boolean noSwap = false;
int startAt = 0;
int stopAt = 9;
while (startAt < stopAt && noSwap == false)
{
noSwap = true;
for (int m=startAt; m<stopAt; m++)
{
if (a[m] > a[m+1])
{
int t = a[m];
a[m] = a[m+1];
a[m+1] = t;
noSwap = false;
}
}
stopAt = stopAt - 1;
}
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
double n = (a[0] + a[1] + a[2] + a[3] +
a[4] + a[5] + a[6] + a[7] +
a[8] + a[9]) / 10;
System.out.println("The minimum number is: " + a[0]);
System.out.println("The maximum number is: " + a[9]);
System.out.println("The average value is: " + n);
System.out.println("The median is: " + a[4]);
}
}
New Code
import java.util.Scanner;
import java.math.*;
public class MakeMeBetterImproved {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int array = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
int MyIntArray = array + i;
}
System.out.println("The minimum number is: " + math.min);
System.out.println("The maximum number is: " + math.max);
System.out.println("The average value is: " + math.average);
System.out.println("The median is: " + math.median);
}
}
Consider using a more dynamic structure than a primitive array.
I like ArrayLists: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Reorganize your long code into while or for loops.
An example:
ArrayList<Integer> a = new ArrayList<Integer>();
Scanner b = new Scanner(System.in);
Integer c = null;
while (a.size() != 10) {
System.out.println("Please input a number in the range 1-19 :> ");
c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
c = b.nextInt();
}
a.add(c);
}
System.out.println("\nArray contents");
for (int i=0; i<10; i++) {
System.out.print((a.get(i) < 10 ? " " : "") + a.get(i) + " ");
}
(And so on...)
Could you try this? I made a few changes.
package p2;
import java.util.Arrays;
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int sum = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
sum += numbers[i];
}
Arrays.sort(numbers);
System.out.println("The minimum number is: " + numbers[0]);
System.out.println("The maximum number is: " + numbers[9]);
System.out.println("The average value is: " + sum / numbers.length);
System.out.println("The median is: " + median(numbers));
}
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
}