My code does not give errors, however it is not displaying the minimum and maximum values. The code is:
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0; i < array.length; i++) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999) {
break;
}
array[i] = next;
// get biggest number
getMaxValue(array);
// get smallest number
getMinValue(array);
}
System.out.println("These are the numbers you have entered.");
printArray(array);
// getting the maximum value
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
// getting the miniumum value
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
Do I need a system.out.println() to display it, or should the return work?
Here is the working code to find the min and max in the array.I hope you will find it helpful:
your maximum, minimum method is right
but you don't print int to console!
and... maybe better location change (maximum, minimum) methods
now (maximum, minimum) methods in the roop. it is need not.. just need one call
i suggest change this code
//To Find Max and Min value in an array without sorting in java
You can try this too, If you don't want to do this by your method.
You just throw away Min/Max values:
You can do something like
Yes you need to use a
System.out.println
. But you are getting the minimum and maximum everytime they input a value and don't keep track of the number of elements if they break early.Try:
Then you will have to pass length into the methods to determine min and max and to print. If you don't do this, the rest of the fields will be 0 and can mess up the proper min and max values.