The problem is in this block of code.
if (Math.abs(array[i]) > max){ max = array[i]; }
You compare the absolute value of the array[i]
element with the non-absolute value of the variable max
. I assume that you are looking for an element in the array for the maximum absolute value. Otherwise, in general, it is not clear why you use the abs
method.
At least you should write
if (Math.abs(array[i]) > Math.abs( max ) ){ max = array[i]; }
In addition, this algorithm is usually performed as follows. First, max
is set equal to the value of array[0]
. Then use a loop, starting with a loop count of 1.
Here is a minimal demo program that shows how to find the maximum in absolute value and just the maximum.
import java.util.*; import java.lang.*; import java.io.*; class Ideone { public static void main (String[] args) throws java.lang.Exception { int[] array = { -100 , -5, 80, 999, 666, -3333 }; int max_abs = array[0]; int max = array[0]; for ( int i = 1; i < array.length; i++ ) { if ( Math.abs( max_abs ) < Math.abs( array[i] ) ) { max_abs = array[i]; } if ( max < array[i] ) { max = array[i]; } } System.out.println( "Absolute maximum value is " + Math.abs( max_abs ) ); System.out.println( "Maximum value is " + max ); } }
The output of the program to the console:
Absolute maximum value is 3333 Maximum value is 999
Compare the results.
As for this item
3.If there are several maximum numbers, you need to display it.
then you should put it in a separate question. That is, in one question, deal with negative numbers, and in another question, solve a completely different problem by providing the appropriate code, and indicating that you do not succeed. Most likely you will need to use an ArrayList
for this purpose.
Math.abs
functionMath.abs
... - Akina