2

So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help. Here's the complete question:

Write a program in which the main method creates an array with 10 slots of type int. Assign to each slot a randomly-generated integer. Call a function, passing it the array. The called function should RETURN the largest integer in the array to your main method. Your main method should display the number returned. Use a Random object to generate integers. Create it with

Random r = new Random(7);

Generate a random integer with

x = r.nextInt();

So, here's what I have so far:

import java.util.Random;
public class Q1 {

    public static void main(String[] args) { 
    Random r = new Random(7);
    int[] count = new int[11];
    int x = r.nextInt();
    for (int i = 0; i < count.length; i++)
    {
        count[i] = x;
    }
}

I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.

I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.

Any help is really appreciated because I really want to understand what's going on here. Thank you!

4
  • You are almost done. Add a new method in your code findMax with argument int array. iterate the loop and find larges number within the array and return it. in main method invoke findmax and print the result. And int x = r.nextInt(); must be inside for loop Commented Oct 22, 2018 at 4:55
  • The idea is that each array element is a new random integer, not all the same. Commented Oct 22, 2018 at 4:56
  • You didn't create an array with ten random integers. You created an array with one random integer repeated eleven times. Get rid of the variable x and change the body of the for loop to count[i] = r.nextInt();. Your next step would be to write the requested function, which should probably have a signature something like static int findMax(int[] array) { ... }. Commented Oct 22, 2018 at 4:56
  • I have added answer about how to make int method and calculate max number.from array. Use code and ask if anything is not clear. All the best :) Commented Oct 22, 2018 at 5:03

7 Answers 7

2

Here is how to generate Random ints

public static void main(String[] args) {
     int []count = new int[10];
          Random r = new Random(7); 
          int x=0;
        for (int i = 0; i < count.length; i++)
        {
            x = r.nextInt();
            count[i] = x;

        }
       System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number

Here is how to make method and get max number from list.

static int maxNumber(int[] mArray){//Passing int array as parameter
        int max=mArray[0];
        for(int i=0;i<mArray.length;i++){
            if(max<mArray[i]){//Calculating max Number
                max=mArray[i];
            }
        }

        return max;//Return Max Number.
    }

Ask if anything is not clear. This is how we make method which return int.

Sign up to request clarification or add additional context in comments.

3 Comments

He wants/needs to generate random numbers with a Random Object though. And I am not sure whether someone struggling with arrays already knows how to use methods.
The exercise of OP requires to use Random r = new Random(7);
@joelfischerr and LuCio, Thank you for point it out. i have update my Code.
1

You can do it by using a simple for loop for the Array. First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this

a < count[i]

and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable

Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps

Comments

1

What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:

import java.util.Random;
public class Q1 {

    public static void main(String[] args) { 
    Random r = new Random(7);
    int[] count = new int[11];
    for (int i = 0; i < count.length; i++)
    {
        int x = r.nextInt(); // You need to generate a new random variable each time
        count[i] = x;
    }
}

Note that this code is not optimal but it is the smallest change from the code you already have.

To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:

int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
        {
            if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
               largest = count[i]; // The current value is larger than any value we have seen so far, 
                                  // we therefore set our largest variable to the largest value in the array (that we currently know of)
               }
        }

Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.

1 Comment

> "This can be done in one single for loop , please check my answer below" This is literally what I wrote in the last two sentences.
1

Your code should be something like this. read the comments to understand it

public class Assignment {



    public static int findMax(int[] arr) {       // Defiine a function to find the largest integer in the array
        int max = arr[0];          // Assume first element is the largest element in the array
        for (int counter = 1; counter < arr.length; counter++)  // Iterate through the array 
        {
             if (arr[counter] > max)  // if element is larger than my previous found max
             {
              max = arr[counter]; // then save the element as max
             }
        }
        return max;  // return the maximum value at the end of the array
    }




    public static void main(String[] args) { 

    int numberofslots =10;

    int[] myIntArray = new int[numberofslots];  // creates an array with 10 slots of type int

    Random r = new Random(7);

    for (int i = 0; i < myIntArray.length; i++)  // Iterate through the array 10 times
    {

     int x = r.nextInt();
     myIntArray[i] = x;  // Generate random number and add it as the i th element of the array.
    }

    int result =  findMax(myIntArray); // calling the function for finding the largest value 
    System.out.println(result); // display the largest value

    }
}

Hope you could understand the code by reading comments..

1 Comment

Random r = new Random(7); should be outside for loop - creating random with the same speed and calling next each time once time will generate the same 'random' number. So we will have array files with the same number
1

This can be done in one simple for loop no need to have 2 loops

public static void main(String[] args) {
        Integer[] randomArray = new Integer[10];
        randomArray[0] = (int)(Math.random()*100);
        int largestNum = randomArray[0];
        for(int i=1; i<10 ;i++){
            randomArray[i] = (int)(Math.random()*100);
            if(randomArray[i]>largestNum){
                largestNum = randomArray[i];
            }
        }
        System.out.println(Arrays.asList(randomArray));
        System.out.println("Largest Number :: "+largestNum);
    }

3 Comments

Hint: Or just Arrays.toString(randomArray) instead of Arrays.asList(randomArray)
And note the exercise of OP requires to use Random r = new Random(7);
This is incorrect as using the Random class is required.
1

Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value. OR you can sort the array and return. Good luck!

3 Comments

You would never sort the array just to get its maximum value. This would be too slow.
Sorting has a minimal asymptotic runtime of O(n * log(n)) compared to iterating through an array once in O(n). So sorting is a worse option in this case. It could be better if you need the n/2 largest values though.
@joelfischerr even for the n/2-th element there are better alternatives than sorting (see quickselect for example).
0

Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)

public int largestValue(){
  int largestNum;
  int[] nums = new int[10];
  for (int n = 0; n < nums.length; n++){
    int x = (int) (Math.random() * 7);
    nums[n] = x;
    largestNum = nums[0];
    if (largestNum < nums[n]){
      largestNum = nums[n];
    }
  }
  return largestNum;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.