the code it's for education in college I need the user to insert a values of array and find which number is the highest and lowest but the lowest number doesn't work . can anyone explain this to me , sorry for asking much
int m=Integer.parseInt(JOptionPane.showInputDialog("Enter index"));
int values;
int num [] = new int [m];
int max = num[0];
int min = num[0];
for (int i=0;i<num.length;i++)
{
num[i] = values =Integer.parseInt(JOptionPane.showInputDialog("Enter value"));
System.out.println(num[i]);
if (num[i] > max)
{
max=num[i];
}
if (num[i] < min )
{
min=num[i];
}
}
System.out.println("Largest Number in a given array is : " + max);
System.out.println("Smallest Number in a given array is : " + min);
You can use Arrays.sort()
to sort the array and simply access the first(0th) index which will hold the smallest number, and the last index which will hold the largest number:
int m=Integer.parseInt(JOptionPane.showInputDialog("Enter index"));
//int values; dont need this
int num [] = new int [m]; //num is initialised with length entered by the user
//int max = num[0]; no need
//int min = num[0]; no need
for (int i=0;i<num.length;i++)
{
num[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter value"));
System.out.println(num[i]);
}
Arrays.sort(num); //this will sort your array in ascending order: smallest number will be at the 0th index and largest will be at the last index
System.out.println("Largest Number in a given array is : " + num[num.length-1]);
System.out.println("Smallest Number in a given array is : " + num[0]);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments