Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my self study of Java, I'm trying to get the largest number from each of the 2 arrays

I don't know why the following output is being executed:
VB
Largest: 3
Largest: 8
Largest: 9
Largest: 23
Largest: 33
Largest: 41
Largest: 51


The correct output should be:
Java
Largest: 23
Largest: 51


How could the following code get the largest number? Because (getLargest1[i] > largest) is equal to getLargest1[i] > 0, which largest = 0.

Why should largest = getLargest1[i];?


C#
public class MyProgram
{
    public void start()
    {
        int[] getLargest1 = {3, 8, 4, 9, 5, 5, 23, 14};
        int[] getLargest2 = {33, 23, 41, 9, 17, 51, 23, 45};
        getLargestFunc(getLargest1, getLargest2);
    }

    private void getLargestFunc(int[] getLargest1, int[] getLargest2)
    {
        int largest = 0;

        for (int i = 0; i < getLargest1.length; i++)
        {
            if (getLargest1[i] > largest)
            {
                largest = getLargest1[i];
                System.out.println("Largest: " + largest);
            }
        }

        for (int i = 0; i < getLargest2.length; i++)
        {
            if (getLargest2[i] > largest)
            {
                largest = getLargest2[i];
                System.out.println("Largest: " + largest);
            }
        }
    }
}
Posted

1 solution

Your ddea is good, that code is working correctly.

if (getLargest1[i] > largest)
is a comparison. You are comparing the next number to the yet found biggest number.

largest = getLargest1[i];
is an assignment when you've found a number, that is bigger than the so far found biggest number.



You should move the output behind the loops, so you'd get only the desired output:

Java
public class MyProgram
{
    public static void main(String[] args) 
    {
        new MyProgram().start();
    }
	
    public void start()
    {
        int[] getLargest1 = {3, 8, 4, 9, 5, 5, 23, 14};
        int[] getLargest2 = {33, 23, 41, 9, 17, 51, 23, 45};
        getLargestFunc(getLargest1, getLargest2);
    }
 
    private void getLargestFunc(int[] getLargest1, int[] getLargest2)
    {
        int largest = 0;
 
        for (int i = 0; i < getLargest1.length; i++)
        {
            if (getLargest1[i] > largest)
            {
                largest = getLargest1[i];
            }
        }
        System.out.println("Largest: " + largest);
 
        for (int i = 0; i < getLargest2.length; i++)
        {
            if (getLargest2[i] > largest)
            {
                largest = getLargest2[i];
            }
        }
        System.out.println("Largest: " + largest);
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900