Counter for calculate number of runs in java - java

Here is my code which take an input value and compare it with a random value
I have 15 times to run the code to estimate and get the input value equals to the random value which the code decide ...
I want to make a counter to calculate how many times I did run the code ...
I tried to put count++; in different places in the code but I did not get right answer ... Where do you think that count++; should be put to get number of runs in the out put ...
thanks
Here is my code
package person;
import java.util.Random;
import java.util.Scanner;
public class Cat {
public static void main(String[] args) {
int max = 100;
int min = 0;
int diff = max-min;
Random rn = new Random();
int i = rn.nextInt(diff+1);
i+=min;
for (int k=0; k<15; k++){
int count=0;
Scanner sb = new Scanner(System.in);
System.out.println("Enter your number");
int x = sb.nextInt();
if(x>i){
System.out.println(x+"is bigger than i");
} else if(x<i){
System.out.println(x+"is smaller than i");
} else if (x==i){
System.out.println(x+"is equals to i "+" "+" no. of try"+count);
break;
}
}
}
}

The problem with your approach was that you count was in the loop so it would always be reseted. you can move it outside the loop or just print the counter loop variable.
package person;
import java.util.Random;
import java.util.Scanner;
public class Cat {
public static void main(String[] args) {
int max = 100;
int min = 0;
int diff = max-min;
Random rn = new Random();
int i = rn.nextInt(diff+1);
i+=min;
int k;
for (k=0; k<15; k++) {
Scanner sb = new Scanner(System.in);
System.out.println("Enter your number");
int x = sb.nextInt();
if(x>i) {
System.out.println(x+"is bigger than i");
} else if(x<i) {
System.out.println(x+"is smaller than i");
} else if (x==i) {
System.out.println(x+"is equals to i "+" "+" no. of try"+k+1);
break;
}
}
if(sb !=null) {
sb.close();
}
}
}

That's because you're setting count = 0 in your for loop. move
int count = 0;
above the for loop and add
count++;
at the beginning of the for-loop. If you had it at the end, you wouldn't count the last run when the loop might break out. Having it at the beginning of the loop means you definitely count each time you even start the process of looking for the randomly generated number.
But it would actually be better to just use the look counter k to keep track of the number of time. No need to waste the extra space on another variable when you already have k to keep track of everything. Just be careful because k starts at 0, so make sure you add 1 to your number of runs if using k.

Related

I tried to print Armstrong numbers between two given integers and my code iterates only one time in for and exits after that, can anyone identify why?

I tried to print Armstrong numbers between two given integers and my code iterates only one time in for and exits after that, can anyone identify why?
I am attaching my code here
public static void main(String[] args) {
//armstrong no. bw two integers given
Scanner in= new Scanner(System.in);
System.out.println("Enter 1 no. ");
int fno= in.nextInt();
System.out.println("Enter 2 no.");
int sno= in.nextInt();
int i,sum=0,digits,count=0;
for(i=fno+1;i<sno;++i)
{
//to find no. of digits in i
digits=i;
while(digits!=0){
digits/=10;
++count;
}
//to find a^^n
int times=0;
int dig,n,temp;
n=i;
while (n!=0){
dig=n%10;
temp= (int) Math.pow(dig,count);
sum=sum+temp;
n/=10;
}
if (sum==i)
System.out.print(i+" ");
}
}}
Your sum is outside of your for, and you aren't resetting it. This means on the second iteration sum !=0 and everything will be messed up. Also I suggest using i++ instead of ++i and leaving spaces between cycles, conditions and variable definitions. You should also reset count after each iteration, so your final code should look so your code should look something like this
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter 1 no. ");
int fno = in.nextInt();
System.out.println("Enter 2 no.");
int sno = in.nextInt();
int sum = 0, digits, count = 0;
for(int i=fno+1;i<sno;++i) {
//to find no. of digits in i
digits=i;
while(digits!=0){
digits/=10;
++count;
}
//to find a^^n
int times=0;
int dig,n,temp;
n=i;
while (n != 0){
dig = n%10;
temp = (int) Math.pow(dig,count);
sum = sum + temp;
n /= 10;
}
if (sum == i) {
System.out.print(i + " ");
}
sum = 0;
count = 0;
}
}
}
I tried to edit TCoder12's post. But It was not saved due to this error:
The edit queue is full at the moment - try again in a few minutes!
So, I decided to post another answer. As TCoder12 said your main problem is that you mistakenly put some instructions inside the for loop, and mistakenly put some instructions out of for loop.
Try not to use extra variables and instructions to reduce the complexity of your code and the risk of making unwanted errors. Also, use appropriate names for variables:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter 1 no. ");
int startNumber = input.nextInt();
System.out.println("Enter 2 no.");
int endNumber = input.nextInt();
for(int eachNumber = startNumber; eachNumber < endNumber; eachNumber++) {
int sum = 0, count = 0;
int numberOfDigits=String.valueOf(eachNumber).length();
//to find a^^n
int temp = eachNumber;
while (temp != 0){
sum += (int) Math.pow(temp % 10, numberOfDigits);
temp /= 10;
}
if (sum == eachNumber) System.out.print(eachNumber + " ");
}
}
}

it works but I still get an error message, what am I doing wrong?

My teacher wants us to take a string that was imputed and take a certain increment and pull out the characters at those increments. I have it working but I still get this error message:
java.lang.StringIndexOutOfBoundsException: String index out of range: 21
then it highlights the line of code point = base.charAt(sum):
here is my entire code so that you can see what I am doing.
import java.util.*;
public class EveryOtherCharacter {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a String: ");
String base = input.nextLine();
System.out.print("Enter an increment: ");
int index = input.nextInt();
int a = base.length();
int sum = 0;
char point;
if(index>a) {
System.out.println("Invalid increment: "+index);
}
else {
while (index<=a) {
sum+=index;
point = base.charAt(sum);
System.out.print(point);
}
System.out.println();
}
}
}
First of all, the condition of the while loop should be sum < a, not index <= a, because the last index of an array/string is length-1, and sum is the variable you are incrementing, not index.
Also, another problem is that after the last "legal" cycle, index <= a will return true, and then you are adding index to sum which will take it beyond the bounds of the string. You should implement it as such:
do {
point = base.charAt(sum);
System.out.println(point);
sum += index;
} while(sum < a)
Edit: If you don't want to use a do-while loop, you can implement it like so with a for loop:
for(sum = 0 ; sum < a ; sum += index) {
point = base.charAt(sum);
System.out.println(point);
}

Store random integers in array

package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop

Java 2D array assigning randomly

I have an array a[5][5] and several values. I want to randomly assign values based on random percentages I create. For example one value is 6 and 25% of the elements in the array should have the value 6. With what I have so far: I created the random percentages and I'm able to randomly assign values for different elements in the array. My problem is: more than 25% of the elements have 6. My question is: How do I make sure that when assigning elements with 6, exactly 25% of the elements in the array a[5][5] have that value? I'm new to programming and tried several loops and ifs but nothing is working out for me. Please push me towards the right direction.
25% of 25 is about 6. It is not accurate. Here is a possible solution.
import java.util.Random;
import java.util.Scanner;
public class Matrix25 {
public static void main(String[] args) {
int[][] Matrix = new int[5][5];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number you want to fill the array to 25%: ");
int number = scanner.nextInt();
int percentage=25;
generateMatrix(Matrix,number,percentage);
printMatrix(Matrix);
}
public static void generateMatrix(int Matrix[][],int num, int perc) {
int n;
int max=Matrix.length*Matrix[0].length;
int[] numbers = new int[max];
Random rnd = new Random();
int m = (int)(max * (perc/100.0));
int x=num>m?m-1:m;
for(int i=0;i<max;i++)
numbers[i]=(i<x)?num:i+1;
for(int i=0;i<Matrix.length;i++)
for(int j=0;j<Matrix[i].length;j++) {
n=rnd.nextInt(max);
Matrix[i][j]=numbers[n];
numbers[n]=numbers[max-1];
max--;
}
}
public static void printMatrix(int Matrix[][]) {
for(int i=0;i<Matrix.length;i++) {
for(int j=0;j<Matrix[i].length;j++)
System.out.printf("%3d\t",Matrix[i][j]);
System.out.print("\n");
}
}
}
I would do it like this
import java.util.Random;
import java.util.Scanner;
class Random2darray {
/**
* #param args
*/
public static void main(String[] args) {
// Create array; you specified 5x5 but you probably shouldn't hard code like this
int[][] numbers = new int[5][5];
//Create a scanner to get user input
Scanner scanner = new Scanner(System.in);
//I am not doing anything to make sure they give a decimal so the program won't work
//right if you are not giving a decimal
System.out.println("How much do you want to fill? Enter a decimal.");
//Get a double
double populatePercentage = scanner.nextDouble();
System.out.println("What number do you want to fill with?");
//Get an int
int fillNumber = scanner.nextInt();
//Don't hardcode like this
int fillTimes = numberOfTimesToFill(25, populatePercentage);
//This is declared outside of the loops because otherwise it will be
//reset each time the loop runs
int count = 0;
//Create a random number generator; default seed is current time which is good enough for this
Random rand = new Random();
//Fill the array with numbers
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Check if you have filled with given number enough times
if(count < fillTimes){
numbers[i][j] = fillNumber;
//Increment count by 1; this is how you are keeping track
count++;
}else{
//Otherwise pick a random number generator
//This will pick a random int between 0 - 50 inclusive
int randomNumber = rand.nextInt(51);
//This will make sure that you are not generating random numbers that are the same
//as the number you are filling with; This says if it is the same generate a new number
while(randomNumber == fillNumber){
randomNumber = rand.nextInt(51);
}
//Once we know its random fill the spot in the array
numbers[i][j] = randomNumber;
}
}
}
//Print the array out
printArray(numbers);
}
private static void printArray(int[][] numbers) {
//Just loop through and print every number
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Print with formatting: this says print a digit (%d) followed by a
//tab(\t) and then specifies what number I want to print
System.out.printf("%d\t", numbers[i][j]);
}
//Print a new line after each row
System.out.printf("\n");
}
}
private static int numberOfTimesToFill(int elements, double populatePercentage) {
System.out.println((int)(populatePercentage * elements));
//Cast to an int to truncate the decimal part of the number because you can't have
//a fraction of an element
return (int)(populatePercentage * elements);
}
}
I have commented the code to explain what everything does. However it does not protect against bad user input and it hardcodes the size of the array, you should always try to avoid hardcoding. In this example I did it (and marked where) to be more clear. Also as was mentioned in the comments above, for your situation where you want exactly 25% of 25 is not possible. This is because .25 * 25 = 6.25 and you can't have .25 of an element.

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;

Categories