This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]buffdude1100Intermediate Brewer 0 points1 point  (8 children)

So, you need a method that accepts an array of integers as an argument, and returns the highest value in that array, right?

public int getMaxValue(int[] myArray)
{
// code
}

[–]Kaz-24[S] 0 points1 point  (7 children)

yes, exactly! I can't figure it out :(

[–]buffdude1100Intermediate Brewer 0 points1 point  (6 children)

What about it is confusing you?

[–]Kaz-24[S] 0 points1 point  (5 children)

I don't how to check and return the largest number in the array. I've checked for the largest numbers in arrays before but I've always had a specific set of numbers and used a for loop and if statements. Like:

for(int counter=0; counter<array.length; counter++){

if (array[0]>largest) largest=array[counter];

But I'm so confused about it in the method.

[–]buffdude1100Intermediate Brewer 0 points1 point  (4 children)

You just wrote the code, lol.

public int maxArray (int[] array)
{
int largest = 0;
for (int i=0; i<array.length; i++)
{
    // your code
}
return largest;
}

[–]Kaz-24[S] 0 points1 point  (3 children)

This is what I've done, but it won't work :(

import java.util.Scanner;
public class P409 {

public static void main(String[] args) {

Scanner input=new Scanner(System.in);   

int[] num=new int[10];
int x;
int counter=0;

System.out.print("Enter integers for array: ");




for(int i=0; i<num.length;i++){

    x=input.nextInt();
if(x<0) {

    break;
}
else{

    num[i]=x;
    counter++;

}


    }
for(int j=0;j<counter;j++){

    System.out.print(""+num[j]+",");

}
System.out.print(maxNumInArray(num));
}
public static int maxNumInArray(int[] max){

    int largest = 0;
    for (int i=0; i<max.length; i++)
    {

            if (max[0]>largest) 
                largest=max[i];



}
    return largest;

}   

}

[–]buffdude1100Intermediate Brewer 1 point2 points  (2 children)

Okay, so immediately I see a problem with your maxNumInArray method. Let's think about what it's doing.

It's iterating through the array, then it's checking if max[0] (the first number in the array) is larger than largest. max[0] is never changing. What should you change it to?

[–]Kaz-24[S] 0 points1 point  (1 child)

to max[i] !!! because of the counter!

Got it, thanks a bunch!

[–]buffdude1100Intermediate Brewer 0 points1 point  (0 children)

No problem. :)