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 have created an implementation of radixsort using ArrayLists of integer arrays. The code is functional however as input size increases passed about 100,000 execution time is far too high. I need this code to be able to handle an input of 1,000,000 integers. What can I do to optimize execution time?
public class RadixSort {
public static void main(String[] args) {
// generate and store 1,000,000 random numbers
int[] nums = generateNums(1000000);
// sort the random numbers
int[] sortedNums = radixSort(nums);
// check that the array was correctly sorted and print result
boolean sorted = isSorted(sortedNums);
if (sorted) {
System.out.println("Integer list is sorted");
} else {
System.out.println("Integer list is NOT sorted");
}
}
/**
* This method generates numCount random numbers and stores them in an integer
* array. Note: For our program, numCount will always equal 1,000,000.
*
* #return nums the new integer array
*/
public static int[] generateNums(int numCount) {
// create integer array with length specified by the user
int[] nums = new int[numCount];
int max = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
nums[i] = (int) (Math.random() * max + 1);
}
// return new integer array
return nums;
}
/**
* This method implements a radix sort
*
* #param nums
* the integer array to sort
* #return nums the sorted integer array
*/
public static int[] radixSort(int[] nums) {
// find max number of digits in an element in the array
int maxDigits = findMaxDigits(nums);
// specified decimal place
int digit = 1;
// create 10 buckets
ArrayList<Integer>[] buckets = new ArrayList[10];
// iterate through the list for as many times as necessary (maxDigits)
for (int j = 0; j < maxDigits; j++) {
// initialize buckets as ArrayLists
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new ArrayList<Integer>();
}
// isolate digit at specified decimal place and add the number to the
// appropriate bucket
for (int i = 0; i < nums.length; i++) {
int last = (nums[i] / digit) % 10;
buckets[last].add(nums[i]);
// convert buckets to an integer array
nums = convertToIntArray(buckets, nums);
}
// update digit to find next decimal place
digit *= 10;
}
// return sorted integer array
return nums;
}
/**
* This method converts from an ArrayList of integer arrays to an integer array
*
* #param buckets
* the ArrayList of integer arrays
* #param nums
* the integer array to return
* #return nums the new integer array
*/
public static int[] convertToIntArray(ArrayList<Integer>[] buckets, int[] nums) {
// loop through the ArrayList and put elements in order into an integer array
int i = 0;
for (ArrayList<Integer> array : buckets) {
if (array != null) {
for (Integer num : array) {
nums[i] = num;
i++;
}
}
}
// return new integer array
return nums;
}
/**
* Method to find the max number of digits in a number in an integer array
*
* #param nums
* the integer array to search through
* #return maxLength the max number of digits in a number in the integer array
*/
public static int findMaxDigits(int[] nums) {
// find maximum number
int max = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
// find and return the number of digits in the maximum number
int maxLength = String.valueOf(max).length();
return maxLength;
}
/**
* This method is used for testing correct functionality of the above radixSort
* method.
*
* #param nums
* the integer array to check for correct sorting
* #return false if the array is sorted incorrectly, else return true.
*/
public static boolean isSorted(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
return false;
}
}
return true;
}
}
I am having problems understanding a program I need to write for class. My program works as it should, but the problem states that it wants me to not print within my methods. I am confused on how I should output my values because my methods must be void according to the problem (which doesn't return anything) and I can't print inside of them.
Here is the question:
Design and implement a java program (name it ArrayMethods), that defines 4 methods as follows:
int arrayMax (int[] array)
int arrayMin (int[] array)
void arraySquared (int[] array)
void arrayReverse (int[] array)
Test your methods by creating an array of length 5 within your main method and filling it with random numbers between 1 and 1000. Your program should then display the original array, display the smallest number in the array, display the greatest number in the array, display the revered array, and display the square of each value in the array. You main method shoudl invoke each method exactly once, with each invocation use the original array as the actual parameter. No printing within the methods. Document your code, and organize/space your outputs properly. Use escape characters and formatting objects when applicable.
So again my question is: How do I use those methods without printing anything if I can't return a value? If anyone could give me a clue on how to solve this, it would be greatly appreciated.
import java.util.Random;
import java.util.Arrays;
public class ArrayMethods
{
public static void main (String[] args)
{
int[] array = new int[5];
array[0] = (int)(Math.random() * (1000 - 1)) + 1;
array[1] = (int)(Math.random() * (1000 - 1)) + 1;
array[2] = (int)(Math.random() * (1000 - 1)) + 1;
array[3] = (int)(Math.random() * (1000 - 1)) + 1;
array[4] = (int)(Math.random() * (1000 - 1)) + 1;
System.out.println("The values within the array are: " + Arrays.toString(array));
System.out.println("The maximum value within the array is: " + arrayMax(array));
System.out.println("The minimum value of the array is: " + arrayMin(array));
System.out.print("The values within the array (squared) are: ");
arraySquared(array);
System.out.print("\n");
System.out.print("The array reversed is: ");
arrayReverse(array);
}
public static int arrayMax (int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static int arrayMin (int[] array)
{
int min = 1000;
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public static void arraySquared (int[] array)
{
int[] array2 = new int[5];
for (int i = 0; i < array.length; i++)
{
array2[i] = array[i] * array[i];
System.out.print(array2[i]);
while ( i < array.length - 1)
{
System.out.print(", ");
break;
}
}
}
public static void arrayReverse (int[] array)
{
for(int i = array.length - 1; i >= 0; i--)
{
System.out.print(array[i] + " ");
}
}
}
For the void functions, in C# you'd simply use an "out" or "ref" keyword. If they insist on Java, Java doesn't have an equivalent, but you can do something like that with an object.
public class PassArray
{
public int[] array;
public PassArray(int[] array)
{
this.array = array;
}
}
public static void Reverse(PassArray arrayHolder)
{
int[] reversed = new int[arrayHolder.array.Length];
int j = 0;
for (int i = arrayHolder.array.Length - 1; i >= 0; i--)
{
reversed[j] = arrayHolder.array[i];
j++;
}
arrayHolder.array = reversed;
}
static void Main(string[] args)
{
int[] toReverse = new[] { 10, 30, 2, 1, 3, 100, 340 };
PassArray passedObject = new PassArray(toReverse);
Reverse(passedObject);
// passedObject.array will now have the reversed array
}
Obviously this could can be improved but it should at least give the right idea.
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.