What to put as condition in while loop? - java

I am writing a method that prints guesses = [random number here from 1-50 inclusive] multiple times on a new line until the value is larger than 48. Once it is larger than 48 I try to print the number of guesses it took (No scanner used though, the 'guesses' are the number produced by the Math.random).
Here is example output:
guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5
and this is my output:
guess = 44
guess = 47
guess = 45
guess = 27
total guesses = 4
The reason I am getting almost the same random numbers is because it's in Practice-It.
Here is my code:
public static void makeGuesses(){
int totalGuesses = 0;
double randomNumber = (Math.random() * 50 + 1);
while(randomNumber < 48){
System.out.print("guess = ");
System.out.println(randomNumber + 1);
randomNumber = (int)(Math.random() * 51);
totalGuesses++;
}
System.out.print("total guesses = " + totalGuesses);
}
Currently, I am not getting the last line of required output. What do I need to make the condition on my while loop?

You're on the right track in that you need to cast to int, but you need to cast to int when you generate the number.
Furthermore, if you use your current implementation, you are generating numbers from 0-50, inclusive. You want to generate from 1-50, inclusive. You can fix this by multiplying by 50, then simply adding 1.
int randomNumber = (int) (Math.random() * 50 + 1);

Your first random isn't an int because you forgot the cast
double randomNumber = (int) (Math.random() * 51);
I suggest you make the type an int as well
int randomNumber = (int) (Math.random() * 51);

The problem is that the condition on your while checks a number you have not yet printed. If you use a debugger and step through the code, you will notice this.
int totalGuesses = 0;
int randomNumber;
while (true) {
randomNumber = 1 + (int)Math.floor(Math.random() * 50);
totalGuesses += 1;
System.out.print("guess = ");
System.out.println(randomNumber);
if (randomNumber > 48) break;
}
System.out.print("total guesses = " + totalGuesses);
Sorry I can't format code well on my phone.

When you need to generate random numbers again and again, you should use java.util.Random for this.
public static void makeGuesses() {
int totalGuesses = 0;
Random rdm = new Random();
int randomNumber;
do {
randomNumber = rdm.nextInt(50) + 1;
System.out.println("guess = " + randomNumber);
totalGuesses++;
} while (randomNumber < 48);
System.out.println("total guesses = " + totalGuesses);
}
}
Output :
guess = 15
guess = 29
guess = 26
guess = 14
guess = 3
guess = 1
guess = 49
total guesses = 7

Related

How do I fix my random number while loop?

What I need to do is make a number generator that stops when it generates 10 and shows how many attempts there was until 10 was reached. I also have to use only while loops for this. Here's my code now:
public static int RandomOccurrence()
{
int randNumber = (int)(Math.random()*20 + 1);
int count = 0;
while(randNumber != 11){
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
and here's the function call:
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
But when I run the code it prints "the number generated is 2" infinitely.
Here's a fixed version of your code, which mostly involves moving the line that gets a random number into the while loop:
public static int RandomOccurrence()
{
int randNumber = 0;
int count = 0;
while(randNumber != 10){//I changed the 11 to 10 because you said you wanted to stop at 10
randNumber = (int)(Math.random()*20 + 1);//added
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
System.out.println(RandomOccurrence());
Sample result:
The number generated is 1
The number generated is 4
The number generated is 20
The number generated is 19
The number generated is 10
5
I really prefer to point the user towards the answers for homework problems instead of giving them code that works. Because we're trying to "teach a man to fish."
The problem with the original code is that it must generate another random number within the while loop. The simplest way to do this is to copy-and-paste the same function-call that you used to generate the first one.
P.S.: You'll very quickly now see that "there's more than one way to do it!"
you should update your random number every time the while loop gets executed:
So randNumber = (int)(Math.random()*20 + 1); should be inside the loop
public static int RandomOccurrence(){
int count = 0;
int randNumber = 0;
while(randNumber != 11){
randNumber = (int)(Math.random()*20 + 1);
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
public static void main(String...args){
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
}
I hope I could help
Here's a 1-liner:
long count = IntStream.generate(() -> (int)(Math.random() * 20 + 1))
.takeWhile(i -> i != 11).count();
See live demo.

Balut dice game Java

I'm making a game for an extra assignment for my college and I have to create a dice game known as "balut" I'm having some issues with assigning values to an array, and having the dice values stored within this array.
I'm in week 9 of 11 of my course we've covered arrays and methods however this is a new concept for me. The goal is as follows:
Balut = all five dice have the same number.
Straight = a total of 15 Or 20.
Sixes = 1 or more sixes.
Fives = 1 or more fives.
Fours = 1 or more fours.
10 rounds.
Total scoring of categories.
total of scores.
If no category is met "none" is printed.
I've put at least 14 hours into this and it was intended to be a 6 to 8 hour program and I still am struggling, questioning if I have the intelligence for the course and am hoping someone here can explain what I'm doing wrong or even what I should be studying.
I've tried creating a single array and assigning all dice values to this array, I run into the problem of when it comes to comparing the values I don't know how to do dice 1 == dice 2 == dice 3 etc.
I've then attempted to make 5 arrays 1 for each dice and use the compare array method which again I can only seem to get it to compare 2 arrays or variables I can't get it to compare all 5 like I'm attempting.
public static void main(String[] args) {
int[] Dicearraytotal1 = new int[10];
int[] Dicearraytotal2 = new int[10];
int[] Dicearraytotal3 = new int[10];
int[] Dicearraytotal4 = new int[10];
int[] Dicearraytotal5 = new int[10];
for (int i = 0; i < Dicearraytotal1.length; i++) {
Integer dice1 = (int) (Math.random() * 6 + 1);
Integer dice1val = dice1;
Integer dice2 = (int) (Math.random() * 6 + 1);
Integer dice2val = dice2;
Integer dice3 = (int) (Math.random() * 6 + 1);
Integer dice3val = dice3;
Integer dice4 = (int) (Math.random() * 6 + 1);
Integer dice4val = dice4;
Integer dice5 = (int) (Math.random() * 6 + 1);
Integer dice5val = dice5;
Dicearraytotal1[i] = (dice1val);
Dicearraytotal2[i] = (dice2val);
Dicearraytotal3[i] = (dice3val);
Dicearraytotal4[i] = (dice4val);
Dicearraytotal5[i] = (dice5val);
Integer total = (dice1val+dice2val+dice3val+dice4val+dice5val);
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(Dicearraytotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(Dicearraytotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(Dicearraytotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(Dicearraytotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(Dicearraytotal5));
System.out.println("Total: " + total);
You are missing an end bracket to stop the for loop, so I assume you were attempting to print the arrays each iteration of the loop. I cleaned up your code a lot and you should take note on some of the changes in order to organize your code better which will make it easier to understand.
public static void main(String[] args) {
int[] diceArrayTotal1 = new int[10];
int[] diceArrayTotal2 = new int[10];
int[] diceArrayTotal3 = new int[10];
int[] diceArrayTotal4 = new int[10];
int[] diceArrayTotal5 = new int[10];
int[] totals = new int[10];
for (int i = 0; i < diceArrayTotal1.length; i++) {
diceArrayTotal1[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal2[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal3[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal4[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal5[i] = (int) (Math.random() * 6 + 1);
totals[i] = (diceArrayTotal1[i] + diceArrayTotal2[i] + diceArrayTotal3[i] + diceArrayTotal4[i] + diceArrayTotal5[i]);
}
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(diceArrayTotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(diceArrayTotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(diceArrayTotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(diceArrayTotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(diceArrayTotal5));
System.out.println("Totals: " + Arrays.toString(totals));
}
Additionally I added a totals array that keeps the total for each index instead of printing it every loop like you were doing. You did not add your compare code, so I cannot assist you with that. Let me know if you need any clarification on any changes. I ran this code and it successfully generated the arrays you need and the totals.
public static void main(String[] args) {
int[] results = new int[6]; // This array will hold the number of time each dice was rolled, so for example results[0] is how many 1 s you have results[5] is how many 6 you have
Random random = new Random();
for (int i = 0; i < 5; i++) { // roll the dice 5 times
results[random.nextInt(6)]++; //increase the counter of the appropriate value
}
boolean balut = false;
for (int i = 0; i < 6; i++) {
System.out.println("Number of " + (i+1) + ": " + results[i]);
if (results[i] == 5) {
balut = true;
}
}
if (balut) {
System.out.println("Balut!");
}
}
Here I implemented only the check for the Balut, but the main point is how I am couting the dices results. Hope it helps.

How do I calculate factorial and show working?

Hey I am really new to java and need a little help with this please.
I have some basic code that works fine it calculates the factor of a number lets say 5 and it gives the output answer of in this case "Factorial = 120.00"
That's great but I want it to give me the output like this "5 * 4 * 3 * 2 * 1 = 120.00" but I just can't figure out how to do it.
Thanks for any help
public static void main(String[] args)
{
Scanner kboard = new Scanner(System.in);
int nos1=0;
int total=1;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print("Please enter number to factor ");
nos1 = kboard.nextInt();
for (int x=1;x<=nos1;x++)
{
total = total *x;
}
System.out.println("Factorial = "+df.format(total));
}
This will only get you part of the way there.
this code will print
1 * 2 * 3 * 4 * 5 * = 120
for (int x=1;x<=nos1;x++)
{
System.out.print(x + " * ");
total = total *x;
}
System.out.println(" = " + df.format(total));
I'll let you figure out a way to print it in the order you want and get rid of the last * at the end. there are a few ways.
String s = "";
for (int x = nos1; x >= 1; x--) {
total = total * x;
// print here it will work
if(!s.isEmpty())
s+="*";
s += x;
}
System.out.println(s + "=" + df.format(total));

Strange: Cant get '1' from Math.random

I am using the following code, it generates numbers randomly but the problem is, I am not able to figure out why does not it generate the number 1
int ran, g, d, col, ran2;
double y = 1000 * (Double.parseDouble(t2.getText()));
int x = (int) y;
d = Integer.parseInt(anum.getText());
double c = 10;
int prevrandom = Integer.parseInt(lnum.getText());
lnum.setText("");
lnum.setVisible(true);
for (g = 0; g==0;) {
d = Integer.parseInt(anum.getText());
ran = (int) (Math.random() * (c)); // Random Number Creation Starts
if (ran > (c / 10)) {
g = 1;
ran2 = ((int) (Math.random() * 10)) % 2;
if (ran2 == 1) {
ran = ran * (-1);
}
d = d + ran;
if (d < 0) {
ran = ran * (-1);
d = d + (2 * ran);
}
int a = d - ran;
if(prevrandom==ran){
g=0;
}
if(g==1){
lnum.setText("" + ran);
}
}
}
I call this function(button) from somewhere. The problem comes when the sum ('a') becomes 4, according to my conditions it shouldn't allow any number other than 'one' and thus it goes into infinite loop.
I am talking about ran variable. Which I get after multiplying Math.random with 10^x where x is a positive integer.
Here ran2 is a number with value 1 or 0. As I multiply Math.Random with 10 which gives a 1 digit number and I mod it with 2.
THis is a 14 year old boy new to java. it would be greatful of people out here to help rather than discourage.
Look at the Javadoc:
Returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
If you need integer random numbers, you might be better off with java.util.Random. To generate a random integer in the range a..b (inclusively), you can use
Random random=new Random();
int rnd=a+random.nextInt(b-a+1);
The problem lies in the code
if (ran > (c / 10)) {
The random number gets created which is even equal to one; but here due to the sign '>' it gets rejected.
Use '>=' instead.
ran = (int) (Math.random() * (c)); where c is from 10 to 10^x
This can be 1 as follows.
int c = 1000;
for (int i = 0; i < 1000; i++) {
int count = 0;
int ran;
do {
ran = (int) (Math.random() * (c)); // where c is from 10 to 10^x
count++;
} while (ran != 1);
System.out.println("count: " + count);
}
prints sometime like
count: 1756
count: 86
count: 839
count: 542
count: 365
....
count: 37
count: 2100
count: 825
count: 728
count: 1444
count: 1943
It returns 1 a thousand time in less than a second.

Loop to Find Sum of Digits

I am trying to write a simple and quite useless program to generate a list of all integers 1><1000 where the sum of digits is 11. Every time I run this, I end up in an infinite loop. I've tried different things - for(){}, while(){}, adding a if(count>500){break;} to halt it after the loop counter reaches 500....still nothing...where am I going wrong in this?
Thanks in advance
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
You are using same variable as controller for your fors. Try to change the controller variable within the for structure from number to number1
You are changing the variable here:
---------------------------------
int hPlace = number / 100; number = number - (hPlace * 100);
---------------------------------
Don't do this
number = number - (hPlace * 100);
when your condition is dependent on number
for(int number = 29; number < 1000; number++)
because you have two nested for loops which both of them use the same variable as counter
for(int number = 29; number < 1000; number++) {
for(number = 29;number < 930;number++) {
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100;
**number** = number - (hPlace * 100); // PROBLEM!!!
int tPlace = number / 10;
**number** = number - (tPlace * 10); // PROBLEM!!!
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
if(count>500){break;} to halt it after the loop counter reaches 500....still nothing
This won't work because you're redeclaring count with an initial value of 0 everytime. So the if will always return false.
Also, these following lines:
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
Modify number, which is your loop variable. Your loop will not perform correctly if you modify the loop variable in unexpected ways. Instead, copy the value over to another variable.
Don't change the value of you loop control variable inside the loop, or dangerous things may result. Instead, copy the value into a new variable and use that in the loop.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SumDigits
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a Number:");
String string=br.readLine();
System.out.println("length of Number:"+string.length());
int sum=0;
int number=0;
for(int i=0;i<=string.length()-1;++i)
{
char character=string.charAt(i);
number=Character.getNumericValue(character);
sum=sum+number;
}//for
System.out.println("Sum of digits of Entered Number:"+sum);
}//main()
}//class

Categories

Resources