Randomly generated number of X's - java

I need a program to randomly generate a number, and then out put that number of x's, on there own line, until it outputs a line of 16 x's, and then it will stop. So far my program generates a number but never stops outputting. I'm sure this is my error but not sure what needs to change. Here is my code at this moment.
import java.util.Random;
public static void main(String[] args)
{
toBinary();
randomX();
}
public static void randomX()
{
Random num = new Random();
int ran = num.nextInt(16+1);
int xs = ran;
while(xs <= 16)
{
System.out.print("x");
}
}

Your version has a number of small issues. Here's a suggested set of revisions.
// create your random object outside the method, otherwise
// you're instantiating a new one each time. In the long run
// this can cause awkward behaviors due to initialization.
public static Random num = new Random();
public static void randomX(){
int ran;
do {
ran = 1 + num.nextInt(16); // move the +1 outside unless you actually want 0's
int counter = 0;
while(counter++ < ran) {
System.out.print("x");
}
System.out.println(); // add a newline after printing the x's in a row
} while(ran < 16);
}
The biggest issue is that you need two loops, an outer one for generating new numbers and an inner one for printing the current number of x's.
A secondary problem was that your loop was checking for numbers <= 16. All of your values are <= 16, so it was an infinite loop.
Additional suggestions found in the comments.

To approach this, think of the loops you might need.
You need to print x a certain number of times, that's a loop. I also introduce a variable to keep track of this printing.
You need to keep printing until you hit 16. That's another loop.
public static void randomX(){
Random num = new Random();
int xs = 0;
//This loop keeps going until you reach 16
while(xs <= 16){
xs = num.nextInt(16+1);
int x = 0;
//This loop keeps going until you've printed enough x's
while (x < xs)
{
System.out.print("x");
x++;
}
System.out.println("")
}
}

You can use a auxiliary counter to manage the loop and increase it to exit the loop.
int i = 0;
while (i<xs){
System.out.print("x");
i++;
}
You can check more about java loops here:
Tutorial about java while

Related

Problem with logic of this pattern problem

Here is the question. I have to print this pattern eg For n = 5
For n = 5
****1
***232
**34543
*4567654
567898765
I have written logic for this problem but I am not able to solve it.
I can't make the last pattern print i.e. the decrease one 2 4,3 5,4
Here's my pattern For n = 5
****1
***232
**34544
*4567666
567898888
Can anyone help me out and tell what's wrong with my logic. How to fix it
My code down below
import java.util.Scanner;
import java.lang.*;
public class Main {
public static void main(String[] args) {
solve();
}
public static void solve(){
int n;
Scanner obj = new Scanner(System.in);
n = obj.nextInt();
for(int row =1;row<=n;row++){
int ans1 = row;
int spaces =1;
for( spaces = 1;spaces<=n-row;spaces++){
System.out.print("*");
}
for (int pattern01 = 1; pattern01<=row;pattern01++){
System.out.print(ans1);
ans1 = ans1 +1;
}
for ( int pattern2 = 1 ; pattern2<=row-1; pattern2++){
ans1= 2*row-2;
System.out.print(ans1);
ans1--;
}
System.out.println();
}
}
}
The issue you are having is that you are not decrementing 'ans1' correctly. If you are not sure how to use the debugger then observe your output through the console with print-out statements. Specifically the 3rd loop when 'ans1' is supposed to count backwards. Also, keep in mind the value of 'ans1' after you exit the second for-loop.
This is your second loop when you start to count up from row number variable.
You increment 'ans1' by 1 each iteration.
for (int pattern01 = 1; pattern01 <= row;pattern01++) {
System.out.print(ans1);
ans1 = ans1 + 1;
}
One thing to consider is that you are incrementing 'ans1' and what is the value of it before you enter your third loop to decrement? You need to do something here before you enter the loop and start printing.
Also, in your third loop you are not decrementing correctly. You should be counting backwards, or rather just decrementing by 1.
for(int pattern2 = 1;pattern2 <= row-1; pattern2++){
ans1= 2*row-2; // Your focus should be here, does this look right? Do you need it?
System.out.print(ans1); // You should decrement first and then print
ans1--; // this is correct, but in the wrong spot
}
I know you can pull it off :) You got this.

Facing problem with the output of this code

My friend gave me this code and i cant seem to find the error in it. I am attaching the code below:
import java.util.*;
public class prg {
public static void main(String[] args) {
int n;
int count;
int a=0,b=1;
int c=0;
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
int ar[]=new int[100];
ar[1] = 2;
for(int i=3;i<=n;i+=2)
{
count=0;
for (int j = 2; j < i ;j++ ) {
if (i % j == 0) {
count++;
break;
}
}
if(count==0)
ar[i]=i;
}
for(int i=0;i<=n;i+=2)
{
a = b;
b = c;
c = a + b;
ar[i]=c;
}
for(int i=0;i<14;i++)
System.out.print(ar[i]+" ");
}
}
So, the even index is storing the fibonacci series and the odd index is storing prime number.
Problem: the rest of the code is working fine but the 9th index of 'ar' array is printing 0 i dont know why and because of it the output is showing wrong.
Take input n as 14 and check the code please.
Thankyou in advance.
PS: i have solved this question in one other way so i request you to not give answers like 'try my method, its not efficient'. I just want to know what is going wrong at INDEX 9 of the array.
Edited: facing problem with the Prime Number loop.
When i is 9, your code correctly identifies that it is not a prime number, so count is not 0. This causes this line to not run:
ar[i]=i;
And then you increase i by 2 to check the next odd number. This means that you never set index 9 of the array to anything, so it remains at its default value - 0.
To fix this, you should introduce a new variable possiblePrime to keep track of which number you are checking. Increase this variable every iteration of the outer for loop, and increase i only when possiblePRime is prime. Also, change the above line to:
ar[i] = possiblePrime;
9 is not a prime number, so it sets nothing in the array. 0 is the default value so it gets printed.

Advice with for loop programs

I get the general gist of for loops. I want to know how I could add two variables to the initializer. I also want to count counter and random at the same time. I want it to prints random but not to print 30 of the same number
public class forLoop {
public static void main(String[] args) {
int random = (int) (Math.random() *50) +25;
for(int counter = 0; counter < 30; counter++){
System.out.println(random);
}
}
}
You're generating the random number outside of your loop. Therefore it will exist as the same number every time. The solution is to move the definition inside of the loop.
public static void main(String[] args) {
for(int counter = 0; counter < 30; counter++){
int random = (int) (Math.random() *50) +25;
System.out.println(random);
}
}
In this way, every time through the loop (30 iterations), your code will (1) generate some random number and (2) print that number.
random is getting set to a particular random integer before the loop starts. You are not defining random to be (int) (Math.random() *50) +25 but rather you are executing that and setting random to the result.
The loop then prints out the same thing each time. If you want a new random each time, then you will need to move that statement inside the loop.

Attempting to create chance calculator

I am relatively new to Java and wanted to try and make a code that would randomly generate 2 numbers a set amount of times, and it would track how many times the 2 numbers are the same. Then after X amount of attempts it would calculate the chance of it happening.
# of randoms divided by times they were the same
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
int[] anArray;
anArray = new int[100000];
Random randomGenerator = new Random();
for (int loop = 1; loop < 1000; loop++) {
int random1 = randomGenerator.nextInt(100);
int random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
int number = number + 1;
countArray[number] = loop;
}
if (loop == 1000) {
System.out.println("Took " + loop + " randoms.");
break;
}
else {}
}
}
}
Main issue seems to be getting array to fill and to get ints in/out of the loop.
Here is my version of your code:
import java.util.Random;
import java.util.ArrayList;
public class RandomTest {
public static void main(String[] args) {
ArrayList<Integer> duplicates = new ArrayList<Integer>();
int random1 = 0, random2 = 0;
Random randomGenerator = new Random();
for (int loop = 1; loop <= 1000; loop++) {
random1 = randomGenerator.nextInt(100);
random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
duplicates.add(new Integer(random1));
}
}
for (Integer i : duplicates) {
System.out.println("Duplicate: "+i.toString());
}
}
}
There are a number of problems that your solution contains:
int number = number + 1;
The above will create a new int called number and give it the value null + 1, this is because the above can be split into 2 lines:
int num;
num = num + 1;
The first line will reserve memory space for a variable called num. The second line will try and put the value of (num + 1) into num. As we are calling num and it has not been initialised - this will give us a java.lang.Error (at least that is what I got).
So as you can see, putting number outside the for loop and initialising it like this:
int number = 0;
for (int loop = 1; loop <= 1000; loop++) {
number = number + 1;
}
Will increment the value of number by 1, 999 times.
Which brings me to the next point. The for loop will never make loop = 1000 because the condition will stop the loop before the condition is true, so when the for loop finishes, loop will equal 999. If you wanted the loop to finish on loop = 1000 you should use loop <= 1000. Also, the if condition is not necessary as when the loop finishes it will just carry on with the rest of the code beneath it.
I haven't used number at all in my solution, this is because I used an ArrayList, which is essentially a much more advanced version of an array that can grow dynamically and do loads of other cool stuff. Unfortunately ArrayLists need to contain objects, so I wrap each int inside an Integer object and this is fine. At the end I use a for loop to iterate through the duplicates list, for each result I print it out.
Hope this helps and if you have any questions feel free to comment beneath.
You probably want to do something about this line:
int number = number + 1;
To step through the array, set number to zero
int number = 0;
before entering the loop then increment number with
number = number + 1;

Method for avoiding duplicates when generating a random list of pairs of numbers is not working as it should

I have this code for setting random values to true in a boolean[][], without making any duplicates:
int a = 0;
int b = 0;
int counter = 0;
for (int i=0; i<=50; i++) {
do {
a = randomizer.nextInt(hoogte);
b = randomizer.nextInt(breedte);
/**debug variable*/
counter++;
} while (bommaker[a][b]);
bommaker[a][b] = true;
}
After testing for a while, I noticed something was wrong, so I added a counter to check it. Every time I run the program, there comes a different number out of "counter". One time it was 57 while the other time even 63. But I have set the loop to exactly 51. This means the code isn't working as it should. Can somebody explain why it generates more than 51 numbers, and give a possible solution?
You have to remember that you have a loop within a loop. The OUTTER loop is limited to 51 executions, but the inner loop will cause a random number of iterations (an extra iteration for each time it sees that the array has already been set to true).
Other than the counter value being greater than you expected, what about the code is not working?
move out the counter++ line from do while loop
int a = 0;
int b = 0;
int counter = 0;
for (int i=0; i<=50; i++) {
do {
a = randomizer.nextInt(hoogte);
b = randomizer.nextInt(breedte);
/**debug variable*/
} while (bommaker[a][b]);
counter++;
bommaker[a][b] = true;
}

Categories