i would like to ask, how to compare all elements in the array to get the BIG int and then display it..
heres the code..
import javax.swing.*;
public class compare {
public static void main(String[] args) {
int num[]=new int[10];
for(int x=0;x<num.length;x++){
num[x]=Integer.parseInt(JOptionPane.showInputDialog("Enter"));
}
for(int c=0;c<num.length;c++){
if(num[c]>num[c])
{
}
}
}
}
now, heres my new code.
but, it does not compare the inputted nums
for(int c=0;c<num.length;c++){
if(num[c]>num[c])
{
int large=num[c];
JOptionPane.showMessageDialog(null, "the largest num "+large);
}
You have a few problems in your code.
if(num[c] > num[c])
will check the value at position c
with itself and will always be false. You need to compare the value of num[c]
with the highest value you have seen so far.
int large = num[c];
JOptionPane.showMessageDialog(null, "the largest num "+large);
You declare large
within the loop, meaning that for each iteration (where you enter the if-condition, which you do not, but let's say you did) you declare and assign a new variable called large
and assign it the value of num[c]
. The dialog is also showed from within the loop, which could cause it to be shown many times for different values.
So you need a variable that will hold the maximum value we have seen so far and use this variable in the loop:
int max = num[0];
for(int c = 1; c < num.length; c++) {
if(max < num[c]) {
max = num[c];
}
}
Since max
is equal to the value at index 0 in num
I can start the loop from index 1.
Please try to understand how and why this works.
When this is done, you have the maximum value from num
in the max
variable and you can display your dialog.
JOptionPane.showMessageDialog(null, "the largest num " + max);