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;
}
Related
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).
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"); }
}
}
Ok this is making my brain melt!! the code compiles just fine but it refuses to display the correct answers in the displayAllResults method. Im not sure how to fix this at all. Ive tried making the methods private as well as having them return values instead of being void. as an example, the method sum gets the sum of the elements in array but will not display them. Im getting 0.
//Main
public class Lab_4_Practice {
public static void main(String[] args) {
//Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = (total / randomArray.length);
//Call Methods
random(randomArray);
displayRandom(randomArray);
largest(maxIndex, randomArray);
smallest(minIndex, randomArray);
sum(total, randomArray);
average(total, randomArray);
sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
//***************************************************
//Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
randomArray[i] = (int)(Math.random() * 300);
}
}
//Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
//Method identifies largest index and its element in array
public static void largest(int maxIndex, int[] randomArray) {
for (int l = 1; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
}
//Method identifies smallest index and its element in array
public static void smallest(int minIndex, int[] randomArray) {
for (int i = 1; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
}
//Method calculates sum of elements
public static int sum(int total, int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
total = total + randomArray[i];
}
return total;
}
//Method calculates average of elements
public static void average(int total, int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
i += randomArray[i];
}
}
//Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
//Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
//Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
}
Its always recommended that you do all your calculations/manipulations in a different class rather than in the main class itself. Create a different class and inside that code something like this -
public class Example{
public void assign(int[] Array){
for(int i=0;i<Array.length;i++){
Array[i]=(int)(Math.random()*300);
}
}
public void display(int[] Array){
System.out.println("The 10 elements of the array are:");
for(int i=0;i<Array.length;i++){
System.out.println(Array[i]);
}
}
public int sum(int[] Array) {
int total =0;
for(int i=0;i<Array.length;i++){
total=total+Array[i];
}
return total;
}
//write all other methods here in this class.
}
now in the main class inside the main method just declare the array and pass the array to the different functions as per your requirement, something like this -
public static void main(String[] args) {
int[] randomArray=new int[10];
Example e=new Example();
e.assign(randomArray);//this must be called first to assign the values inside the array.
e.display(randomArray);//call this method if you wish to display the values.
System.out.println("The sum of the elements are: "+e.sum(randomArray));
}
I have done little bit changes in your code. You can compare it with your old code. Most of the places you were facing problem because of local variable. Whatever you were supplying to corresponding method and after operation changes made on local variable is not affecting your instance variables. And for largest() and small() method(), you were calling it without sorting your array, because of that it was giving wrong output.
public class StackProblem {
public static void main(String[] args) {
// Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = 0;
// Call Methods
random(randomArray);
displayRandom(randomArray);
sortArray(randomArray);
maxIndex=largest(randomArray);
minIndex=smallest(randomArray);
total=sum(randomArray);
average=average(total, randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
// ***************************************************
// Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int) (Math.random() * 300);
}
}
// Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
// Method identifies largest index and its element in array
public static int largest(int[] randomArray) {
int maxIndex=0;
for (int l = 0; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
// Method identifies smallest index and its element in array
public static int smallest(int[] randomArray) {
int minIndex=0;
for (int i = 0; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
// Method calculates sum of elements
public static int sum(int[] randomArray) {
int localTotal=0;
for (int i = 0; i < randomArray.length; i++) {
localTotal+=randomArray[i];
}
return localTotal;
}
// Method calculates average of elements
public static int average(int total, int[] randomArray) {
return total/randomArray.length;
}
// Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
// Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
// Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
[Nobody supports my motion to put this on hold due to [duplicate] - so I feel compelled to write an answer here.]
This is the typical pattern for a method calculating some value from the elements of an array:
public static int largest(int[] array) {
int maxIndex = 0;
for (int l = 1; l < array.length; l++) {
if (array[l] > array[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
And you call it like this:
int maxIndex = largest( randomArray );
Parameters with a type of int, long, double, char, short, float, boolean are copied "by value", i.e., the corresponding expression in the call - the actual parameter - is evaluated and the result is stored in a variable with the name of the parameter. This variable is short-lived: when you return from the method call, it is gone. The only way to hand back the value is by using the return mechanism in a non-void method.
If you have an array however, things are a little different. An array is an object, and objects are handled via references, values that tell the computer where the object can be found. This reference is also copied from the point of invocation and stored in a short-lived variable, but you still can access the object it references so that changes of an array (or any object) are possible via code in a method with an object reference as a parameter.
Finally, the code for calculating the average is very much in error.
public static double average( int[] array ) {
return (double)sum( array )/array.length;
}
and you need a variable of type double to hold the result. (There is a chance that an array might have the length 0, so I'm a little careless there. Do you see why?)
The variables you are passing to each method are all zero. You need to change those within the main method, since variables in methods are only used and modified within their respective methods, even if they were passed to that method from the main method. It looks like this is what you want:
randomArray = random(randomArray);
displayRandom(randomArray);
maxIndex = largest(maxIndex, randomArray);
minIndex = smallest(minIndex, randomArray);
total = sum(total, randomArray);
average(total, randomArray); //not sure what you're trying to do here; this method does not calculate the average
average = total/randomArray.length; //you probably just want to use this instead of the average() method
randomArray = sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
Additionally, for each method that is supposed to return a value, you will need to change the return type in the method header from void to the appropriate variable type, as well as add a return statement at the end of each method.
Add three methods, one that will return the maximum value in the array (FindMax), one that will return the minimum value in the array (FindMIn) and one that will return the average of the values in the array (FindAvg).
import java.util.Scanner;
public class methods {
public static void main(String[] args) {
int [] numbrs;
numbrs = new int[25];
int i = 0;
System.out.println();
populateArray(numbrs, numbrs.length);
System.out.println("\n********** the array reversed is **********\n");
for (i = numbrs.length - 1; i >= 0; i--)
System.out.println(numbrs[i]);
System.out.println("\n***** end of Array01.java *****");
} // end of main method
/* ********************************************************
Pre Condition: an array of n integers where n is given.
Post Condition: an array populated with randomly
generated integers in the range of 1 to limit
specified by the user.
******************************************************** */
public static void populateArray(int [] arry, int lm) {
Scanner kBd;
int lim = 0;
kBd = new Scanner(System.in);
System.out.print("Enter the upper limit of random numbers...");
lim = kBd.nextInt();
System.out.println();
int x = 0;
for(int i = 0; i < lm; i++) {
arry[i] = getRandomInt(lim);
System.out.println(arry[i]);
}
} // end of populateArray method
/* ********************************************************
Pre Condition: an integer for the upper limit of the
random number to generate.
Post Condition: an integer in the range of 1 to limit
******************************************************** */
public static int getRandomInt(int limit) {
return (1 + (int)(Math.random() * limit));
} // end of getRandomInt method
public static int max(int highest) {
} // end of class Array01
Merry Christmas. I am in a giving mood today. This is how you figure out the greatest value in the array:
public static int max(int[] array)
{
int highest = array[0];
for (int i = 1; i < array.length; i++)
{
if (array[i] > highest)
{
highest = array[i];
}
}
return highest;
}
Basically, assume the first stored value is the greatest value and compare it to the next value. If the next value is the greatest, assign to highest variable. Continue iterating through the array until you examine each and every value. One pass, and you are done.
For my current homework, I'm trying to sort my array through a generic class as the user inserts values into its locations. When the size reads as fully loaded, the array class calls in an expansion method that increases the size of the array while retaining its values in proper locations, which I followed from my Professor's note. For some reason, all my values except for location[0] seem to either be misplaced or erased from the array. I'm leaning that the problem originates in the expansion method but I have no idea how to fix this.
For example, the initial size is currently set to 5 but increments by 3 when expansion method is called. The user can input values 1,2,3,4,5 perfectly. But expansion is called when user inputs new value 6 that outputs an array of 1, 6, null, null, null, null. Any further will lead to the error "Exception in thread "main" java.lang.NullPointerException"
Here is my Sorted Array class:
public class SortedArray {
private int size;
private int increment;
private int top;
Comparable[] a;
public SortedArray(int initialSize, int incrementAmount)
{
top = -1;
size = initialSize;
increment = incrementAmount;
a = new Comparable [size];
}
public int appropriatePosition(Comparable value)
{
int hold = top;
if(hold == -1)
{
hold = 0;
}
else
{
for(int i = 0; i <= top; i++)
{
if(value.compareTo(a[i]) > 0)
{
hold = i + 1;
}
}
}
return hold;
}
public Comparable smallest()
{
return a[0];
}
public Comparable largest()
{
return a[top];
}
public void insert(Comparable value)// the method that my driver calls for.
{
int ap = appropriatePosition(value);
//Expansion if full
if(full() == true)
{
expansion();
}
//Shifting numbers to top
for(int i = top; i >= ap ; i--)
{
{
a[i + 1] = a[i];
}
}
a[ap] = value;
top++;
}
public boolean full()
{
if(top == a.length -1)
{
return true;
}
else
{
return false;
}
}
public void expansion()//here's where the expansion begins
{
int newSize = a.length + increment;
Comparable[] tempArray = new Comparable[newSize];
for(int i= 0; i < a.length; i++)
{
tempArray[i]= a[i];
a = tempArray;
}
}
Here's my driver class that calls for the insert method in SortedArray class.
public class IntDriver {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Creating variables
int data;
boolean check = false;
int choice;
int size = 5;
int increment = 3;
SortedArray b = new SortedArray(size, increment);
//Creating Menu
System.out.println("Please choose through options 1-6.");
System.out.println("1. Insert\n2. Delete\n3. Clear\n4. Smallest\n5. Largest\n6. Exit\n7.Redisplay Menu");
while(check == false)
{
choice = keyboard.nextInt();
switch(choice)
{
case 1:
System.out.println("Type the int data to store in array location.");
data = keyboard.nextInt();
Integer insertObj = new Integer(data);
b.insert(insertObj);
System.out.println("The value " + data + " is inserted");
b.print();
break;
In the expansion method, you're replacing a too soon. The replacement should happen after the for loop:
public void expansion()//here's where the expansion begins
{
int newSize = a.length + increment;
Comparable[] tempArray = new Comparable[newSize];
for(int i= 0; i < a.length; i++)
{
tempArray[i]= a[i];
}
a = tempArray;
}