I'm trying to write a program to generate a random 3 digit number and reverse it, and so I wrote out two methods where getRandomNum generates the number and reverseDigits reverses it. However the 2nd method doesn't take in the random number generated from the 1st method, as the 1st method shows a 3 digit number but the 2nd method shows 0 when running the code.
I've tried looking up how to share variables between methods and it seems that I need to use static variables outside the methods. But it still shows 0 for reverseDigits.
Am I missing something or is there something else to be done?
public class MathTrick
{
static int upperBound = 999;
static int lowerBound = 100;
//generate random 3 digit number
static int getRandomNumber = 0;
static int mDifference = 0;
public static void main(String[]args)
{
getRandomNum();
reverseDigits();
}
static void getRandomNum()
{
int upperBound = 999;
int lowerBound = 100;
//generate random 3 digit number
int getRandomNumber = 0;
int mDifference = 0;
while (mDifference <= 1)
{
getRandomNumber = (int)(Math.random()*((upperBound-lowerBound)+1)) + lowerBound + 1;
int x = (int)(getRandomNumber/100);
int y = getRandomNumber%10;
mDifference = Math.abs(x-y);
}
int m = getRandomNumber;
}
static int m = getRandomNumber;
static void reverseDigits()
{
int a = m, reverseDigits = 0;
while (a != 0)
{
int remainder = a % 10;
reverseDigits = reverseDigits * 10 + remainder;
a = a / 10;
}
int n = reverseDigits;
}
}
The direct answer to your question
Replace this line int m = getRandomNumber; with m = getRandomNumber;
Basically, you overshadowed the static variable m with a local variable int m.
A few changes, here they are (my proposal).
Change that both methods to return an integer getRandomNum returns a new random number, and the reverseDigits method returns reversed number. Additionally, reverseDigits get a parameter - a number that should change.
So, after changes.
public static void main(String[] args) {
int randomNum = getRandomNum();
int reverse = reverseDigits(randomNum);
System.out.println(randomNum);
System.out.println(reverse);
}
static int getRandomNum() {
//
return getRandomNumber;
}
static int reverseDigits(int m) {
//
return reverseDigits;
}
And you can remove other static fields.
Your methods need return statement, this could help you :
public class MathTrick {
// generate random 3 digit number
private int getRandomNumber = 0;
private int mDifference = 0;
private int m = getRandomNumber;
public static void main(String[] args) {
MathTrick application = new MathTrick();
System.out.println("getRandomNum() return: " + application.getRandomNum());
System.out.println("reverseDigits() return: " + application.reverseDigits());
}
private int getRandomNum() {
while (mDifference <= 1) {
int upperBound = 999;
int lowerBound = 100;
getRandomNumber = (int) (Math.random() * ((upperBound - lowerBound) + 1)) + lowerBound + 1;
int x = (int) (getRandomNumber / 100);
int y = getRandomNumber % 10;
mDifference = Math.abs(x - y);
}
m = getRandomNumber;
return getRandomNumber;
}
private int reverseDigits() {
int a = m, reverseDigits = 0;
while (a != 0) {
int remainder = a % 10;
reverseDigits = reverseDigits * 10 + remainder;
a = a / 10;
}
return reverseDigits;
}
}
Your methods are void,try something like this by making them return int
static int getRandomNum(){
//some code
return n;
}
static int reverseDigits(int n){
//some code
return n;
}
int m = getRandomNumber; has scope of only method getRandomNum(); To get random number to another method, variable m should be declared on class level.
first generate the random number than pass it in the reverse function.
static int getRandomNum(){
//generate random number and return that number
return n;
}
static int reverseDigits(int n){
//reverse number code and return the number
return n;
}
public static void main(String[]args)
{
int number = getRandomNum();
int reverse = reverseDigits(number);
}
You can imagine Methods as boxes anything declared inside a method will be only visible to that method, so to have a variable Visible to all methods inside a class, the variable should be declared at the top of the class outside of all methods,and plus u should know how the variables declaration and initialization works The first Answer in this post explains them really well because i noticed you declared the variable multiple times, lets say the value that u needed was inside the first declared variable, when u declare the same variable again that old value will not be read from inside the method used to declare a second time and as a good practice u should have the variable as private and try not to use static variable often unless it is necessary. Example of what you should have:
public class MathTrick{
private int number;
public static void main(String[]args)
{
getRandomNum();
reverseDigits();
}
public void getRandomNumb(){
generate a number...
number = NumberGenerated;
}
public void reverseDigits(){
reverse the digits in variable number..
}
}
public class MathTrick {
public static void main(String[] args) {
int randomNumber = getRandomNumber();
int reverseRandomNumber = getReverseRandomNumber(randomNumber);
System.out.println(randomNumber + "***" + reverseRandomNumber);
}
private static int getRandomNumber() {
return (int) Math.round(Math.random() * 999);
}
private static int getReverseRandomNumber(int num) {
return Integer.parseInt(new StringBuffer("" + num).reverse().toString());
}
}
Try this. It may help you
you should pass the random number to the method that reverse it.
this is what you looking for:
public static void main(String[]args)
{
int rand = getRandomNum();
int reverse = reverseDigits(rand);
System.out.println(rand);
System.out.println(reverseDigits(rand));
}
static int getRandomNum()
{
int upperBound = 999;
int lowerBound = 100;
//generate random 3 digit number
int getRandomNumber = 0;
int mDifference = 0;
while (mDifference <= 1)
{
getRandomNumber = (int)(Math.random()*((upperBound-lowerBound)+1)) + lowerBound + 1;
int x = (int)(getRandomNumber/100);
int y = getRandomNumber%10;
mDifference = Math.abs(x-y);
}
return getRandomNumber;
}
static int reverseDigits(int random)
{
int reverseDigits = 0;
while (random != 0)
{
int remainder = random % 10;
reverseDigits = reverseDigits * 10 + remainder;
random = random / 10;
}
return reverseDigits;
}
Your second method (which is gonna return the reversed number) needs the random generated number as parameter.
Actually, your idea can be written like this:
public class MathTrick
{
static int upperBound = 999;
static int lowerBound = 100;
public static void main(String[] args)
{
final int randomNumber = getRandomNum();
final int reverseRandomNumber = reverse(randomNumber);
System.out.println("Random number: " + randomNumber);
System.out.println("Reverse random number : " + reverseRandomNumber);
}
static int reverse(int num)
{
return Integer.parseInt(new StringBuilder(String.valueOf(num)).reverse().toString());
}
static int getRandomNum()
{
return ThreadLocalRandom.current().nextInt(lowerBound, upperBound);
}
}
Related
So far i have made a random numbers array but i am stuck on how to make a printarray method that i can call within the main. I need to invoke print array in the same class and print out all elements separated by one space
public class HunterIsaacsHw6
{
public static void main(String[] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
}
public static double printArray(doubleArray[]){
for(double n: doubleArray){
System.out.println(n+" ");
}
}
Your method declaration is incorrect and you are not even calling it. Try:
public static void main(String [] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
printArray(doubleArray);
}
public static void printArray(double doubleArray[]){
for(double n: doubleArray){
System.out.println(n);
}
}
Also, nothing is being returned from printArray so it should be declared as void
Also I prefer the declaration as double[] doubleArray
edit
Also System.out.println(n); is sufficient, there is no need to append a space
I am new to coding and trying to call a method (RandomArray) which I wrote and defined in a separate class, but in my driver code I am getting following error message:
Couldn't find symbol- RandomArray().
the code SHOULD create an array (size of which is chosen by the user) and then populate it with random numbers and output the Highest, Lowest, and Average of the numbers in said array.
All spellings match up, and the call itself works and displays no errors, but when using it in the for-loop I get the error message.
This is the class where I created the method:
import java.util.Random;
public class RandomArray
{
//things declared at class level
public int minimun,maximun,adverage, mn, mx, avg;
public String range;
//constucotr for inital numbers
public RandomArray()
{
minimun = 0;
maximun = 1000 + 1;
}
static int RandomArray()
{
Random ran = new Random();
return (ran.nextInt(1000) + 1);
}
//define types
public RandomArray (int mn, int mx, String r, int a)
{
minimun = mn;
maximun = mx;
range = r;
adverage = a;
}
//set minimun
public void setMinimun (int m)
{
minimun = mn;
}
//get minimun
public int getMinimun()
{
return minimun;
}
//set maximun
public void setMaximun(int x)
{
maximun = mx;
}
//get maximun
public int getMaximun()
{
return maximun;
}
//compute adverage
public int adverage(int...array)
{
int adverage = 0;
if (array.length > 0)
{
int sum = 0;
for(int num : array)
sum = sum + num; //add numbers in array
adverage = (int)sum / array.length; //divide numbers in array by the array lenth
}
return adverage;
}
//return values as a string
public String toString()
{
return String.valueOf(getMinimun() + getMaximun() + adverage());
}
}
And this is the driver program that should be populating the array (of users choice) with random numbers and printing the highest, lowest and average:
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class DemoRandomArray
{
// variable go here
final int minimun = 0;
public static void main(String[] args)
{
final int max = 100;
RandomArray ra = new RandomArray();
int[] anArray = new int[1000];
for(int i=1; i < max; i++)
{
System.out.println(RandomArray());
}
}
}
The method is inside another class, so you need to use the class name.
RandomArray.RandomArray() instead of just RandomArray()
I am just starting out in Java and I have searched through the internet for several hours and cannot seem to find something to help me on an assignment. I have an array and I need to write a method for it. It seems easy but I cannot seem to connect the two together. I understand the methods but we did not go over using them with arrays so I am totally confused. If there is a similar answer on here, please point me in the right direction.
Thank you for your time.
Question:
Write a method which takes in an integer from the user between 1 and 10 and determines if that number is part of the randomly generated array. It must have a method signature of (int []) and return a boolean.
public class ArrayExample {
public int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
public static void main(String [] args) {
}
}
It will be something like below:
public class ArrayExample {
public static int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
private static boolean checkForNumInArray(int[] randomArrayInput){
//your logic goes here
// ask user for input number - Scanner/BufferedReader
//search for that number in array - Loops
// if found return true, otherwise return false - if-else
}
public static void main(String [] args) {
int[] randomArray = createRandomArray();
boolean isPresent = checkForNumInArray(randomArray);
}
}
You can go through the code to have understanding
public class ArrayExample {
public int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
public int getUserInput() {
//Take input from user and check it is between 1 and 10.
}
public boolean search(int[] arr, int input) {
// Use some searching algorithm. Linear search will suit as the array is randomly generated.
// if input is present in array return true else return false.
}
public static void main(String [] args) {
int input = getUserInput();
boolean result = search(createRandomArray(), input);
//Print a message based on result.
}
}
In the main method you simply have to iterate the loop of integers from one to ten and check if it is present in the array you have created.
public static void main(String[] args) {
int arr[] = createRandomArray();
for(int i=0;i<=10;i++) {
if(Arrays.binarySearch(arr, i) == 0) { System.out.println("yes"); }
}
}
Hi I have been having difficulty in creating a set interface that allows me to add integers to a set using an array? My biggest problem is that calling the method I don't know how to iterate through the array so that the next integer is added to the array after the previous and so forth.
public class SetInt
{
static final int LOWERRANGE = 1;
static final int UPPERRANGE = 49;
static final int NOTAMEMBER = 0;
//class constants used to represent the range of values this set can hold
//and a dummy value of 0 to represent nothing in the set
int[] anArray = new int[50];
public void add(int a)
{
anArray[1] = LOWERRANGE;
anArray[a] = a;
}
/* prints the set of numbers currently in the set
*/
public void printNumbers()
{
for(int num = 2 ; num <=47; num++)
{
if(anArray[num] != 0)
{
System.out.print(" " + anArray[num]);
}
}
}
/* return the minimum value in the set
* #return the minimum value
*/
public int min()
{
int minValue = anArray[0];
for(int i=1; i<anArray.length; i++)
{
if(anArray[i] < minValue)
{
minValue = anArray[i];
}
}
return minValue;
}
I need to make a class that has a public method roll() which will return a random int between 1 and 6. Then I need to make a tester program that measures the frequency of rolls meaning it counts up how many ones, twos, threes, etc. in 1000 rolls.
My die class is as below:
import java.util.Random;
public class Die {
public int roll() {
Random rand = new Random();
int n = rand.nextInt(6) + 1;
return n;
}
}
and this is my tester class:
public class DieTester extends Die {
public static void main(String[] args) {
int ones = 0;
int twos = 0;
int threes = 0;
int fours = 0;
int fives = 0;
int sixes = 0;
for(int i = 0; i < 1000; i++) {
int roll();
if(n == 1) {
ones = ones + 1;
}
if(n == 2) {
twos = twos + 1;
}
if(n == 3) {
threes = threes + 1;
}
if(n == 4) {
fours = fours + 1;
}
if(n == 5) {
fives = fives + 1;
}
if(n == 6) {
sixes = sixes + 1;
}
}
System.out.println(ones);
System.out.println(twos);
System.out.println(threes);
System.out.println(fours);
System.out.println(fives);
System.out.println(sixes);
}
}
However the int roll(); function in the Die Tester class is not working. How can I fix this?
You have two issues:
int roll(); is not a valid statement in its current place
if you want to keep roll the way it is you need to create an instance of Die first, otherwise make it static
Solution using static
public class Die {
public static int roll() {
Random rand = new Random();
int n = rand.nextInt(6) + 1;
return n;
}
}
public class DieTester {
public static void main(String[] args) {
// variables
for(int i = 0; i < 1000; i++) {
int n = Die.roll();
// your if logic
}
// printing
}
}
Solution using an instance of Die
public class Die {
public int roll() {
Random rand = new Random();
int n = rand.nextInt(6) + 1;
return n;
}
}
public class DieTester {
public static void main(String[] args) {
// variables
Die die = new Die();
for(int i = 0; i < 1000; i++) {
int n = die.roll();
// your if logic
}
// printing
}
}
In both cases it does not make much sense to make DieTester extend Die.
luk2302's answer is correct. I think is worth to mention that you can do this a lot easier with Random::ints:
Map<Integer, Long> dieTest = new Random().ints(1000,1,7) // generate 1000 pseudorandom values from 1 to 6
.boxed() // box each int to Integer
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); // group by each distinct value counting the number of its occurrence in the stream
System.out.println(dieTest);
Sample output showing the frequency of each number:
{1=178, 2=158, 3=165, 4=154, 5=183, 6=162}