Trouble calling method and Populating Random Array - java

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()

Related

How to use the value of a method in another method?

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);
}
}

How to pass elements of an array from sub class to main class

So I am very new to learning java and I have a sub class which contains the main and a parent class which does all the calculations. I am having problems on how to pass the elements of an array from the main class to the parent class.
Here is my code. Please help me with how to instantiate the array.
import java.util.Scanner;
public class GreatestLeastAverageApp {
public GreatestLeastAverageApp() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
GreatestLeastAverage number = new GreatestLeastAverage();
int[] x = {0};
int a = 0, b = 0;
x = new int[a];
{
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= a; j++)
GreatestLeastAverage.a[i] = x[j]; // loop to pass the values of the array elements to the parent class from the sub class.
}
}
Scanner keyboard = new Scanner(System.in); // for the input from the user
System.out.println("Enter the number of elements:");
a = keyboard.nextInt(); // enter the number of integers to be entered so loop can run accordingly
System.out.println("Enter a set of integers( Enter -99 to exit):");
do // do loop so the user can input the variables until one of the variable is =-99.
{
{
for (b = 0; b <= a; b++)
x[b] = keyboard.nextInt();
}
} while (x[b] != -99);
//GreatestLeastAverage number = new GreatestLeastAverage(); // object made for parent class.
System.out.println("The Greatest Number is" + number.computegreatest()); // output line.
System.out.println("The Smallest Number is" + number.computeleast());
System.out.println("The average is " + number.computeaverage());
keyboard.close();
}
}
public class GreatestLeastAverage {
static int x; //variables declared for input in super class.
public static int[] a; // static variable to access in both classes.
int temp;
int temp1;
int temp2;
int average;
public int greatestleastaverage(int d) {
d = x;
return x;
}
public static int getarray(int[] b) {
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= x; j++) {
a[i] = b[j];
}
}
return b[];
}
I know you can't return elements of an array but I really need help.
Use Lists. They're generally more flexible, and if you use ArrayList properly, it can be virtually just as performant as an array.
public class GreatestLeastAverage {
// ... other private members
private List<Integer> a = new ArrayList<Integer>();
public List<Integer> getA() {
return a;
}
}
This lets you do code like:
GreatestLeastAverage gla = new GreatestLeastAverage();
for (int b = 0; b <= a; b++) {
gla.getA().add(keyboard.nextInt());
}
If you should require that data for other uses, it's in gla already! Simply reuse it.
for(int a : gla.getA()) {
// Do something with a
}
I'm sure you used static members because you didn't know how to make it work otherwise, but just know that using static members is generally discouraged unless they're final (constant).
You shouldn't pass data (array) to methods in GreatestLeastAverage class by setting the value of the static field (public static int[] a;). Instead you should pass data to methods as theirs arguments. Your program should look like this:
import java.util.Scanner;
public class GreatestLeastAverageApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int numOfElems = input.nextInt();
int[] numbers = new int[numOfElems];
System.out.println("Enter a set of integers:");
for (int i = 0; i < numOfElems; i++) {
numbers[i] = input.nextInt();
}
System.out.println("Statistics:");
System.out.println(" min: " + GreatestLeastAverage.findMin(numbers));
System.out.println(" max: " + GreatestLeastAverage.findMax(numbers));
System.out.println(" average: " + GreatestLeastAverage.findAverage(numbers));
}
}
class GreatestLeastAverage {
public static int findMin(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num < candidate) candidate = num;
}
return candidate;
}
public static int findMax(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num > candidate) candidate = num;
}
return candidate;
}
public static double findAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum / (double) numbers.length;
}
}
To make this code even better:
The min/max/average calculations above are not great, e.g. If you pass empty array to findAverage, then numbers.length will be 0 and you'll divide by 0. You should make those calculations better, see: #1, #2, #3.
Consider using ArrayList instead of array, when you need to dynamically change the size of the list during runtime (See Neil's answer).

Java Methods and Arrays

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"); }
}
}

Hash Table with Linear Probing and Random Numbers

Hi I have the task to show, and count, the trace of operations needed to insert the randomly generated keys, one by one, into an initially empty 101-bucket hash table.
I have created this class to generate 100 random numbers and then insert them into the hash table class, but i dont know how to insert them to the hash table and i do it manually.
I will appreciate if you give me some advice.
The Code:
import java.util.Random;
public class RandomNumbers {
static void main(String[] args) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public RandomNumbers() {
for (int i = 0; i < 100; i++) {
System.out.println(getRandomNumberInRange(0, 15024267));
}
}
public static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
String[] numbersPrinting;
}
As you can see I inserted the random numbers manually.
The Hash Table Code:
import java.util.Arrays;
/**
*
*
*/
public class HashFunction {
String[] theArray;
int arraySize;
int itemsInArray = 0;
int K = 0;
/**
*
*/
public static void main(String[] args) {
HashFunction theFunc = new HashFunction(101);
String[] elementsToAdd2 = {"3638273","3483793","1362909","14908691","14624805","3959017","14208240","8911589","3701879", };
theFunc.hashFunction2(elementsToAdd2, theFunc.theArray);
}
public void hashFunction2(String[] stringsForArray, String[] theArray) {
for (int n = 0; n < stringsForArray.length; n++) {
String newElementVal = stringsForArray[n];
// Create an index to store the value in by taking
// the modulus
int arrayIndex = Integer.parseInt(newElementVal) % 101;
System.out.println("P" + arrayIndex + " " + "I" + newElementVal + "#" + arrayIndex );
// Cycle through the array until we find an empty space
while (theArray[arrayIndex] != "-1") {
++arrayIndex;
System.out.println( "P" + arrayIndex);
// If we get to the end of the bucket go back to index 0
arrayIndex %= arraySize;
}
theArray[arrayIndex] = newElementVal;
}
}
HashFunction(int size) {
arraySize = size;
theArray = new String[size];
Arrays.fill(theArray, "-1");
}
}
I don't know how to insert the random numbers from the random numbers class into the Hash Table class
I think what you should do is create Random numbers in the main function of HashFunction class:
public static void main(String[] args) {
HashFunction theFunc = new HashFunction(101);
String[] elementsToAdd2 = new String[101];
for (int i = 0; i <= 100; i++) {
elementsToAdd2[i] = Integer.toString(RandomNumbers.getRandomNumberInRange(0, 15024267));
}
theFunc.hashFunction2(elementsToAdd2, theFunc.theArray);
}
With this way, you will have access to Random Numbers array in HashFunction class and you can add it in theArray array of HashFunction class.

Set Interface Design

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;
}

Categories