Home > Blockchain >  Lowest value is always 0 in 2d array
Lowest value is always 0 in 2d array

Time:01-13

New guy here trying 2D arrays. I have these codes but whenever I run it, the lowest value would always end up with 0 even if I input non-zero digits. Any idea how to fix this?

import javax.swing.JOptionPane;

public class TwoDArrayActivity {
    
    public static void main(String[] args){
        
        // declaration of array
        int a[][] = new int[3][3];  

        int i = 0; // rows
        int j = 0; // columns
        String display = ""; 

        int low = a[i][j];
        
        for(i=0; i < a.length; i  ) {   // count the number of rows
            
            for(j = 0; j < 3; j  ) {      // count the number of columns
                a[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Enter a Number to Array ["   i   "]"   "["   j   "]"));
                
                if(a[i][j] < low) 
                    low = a[i][j];
                display = display   a[i][j]   "     ";
            } // end of inner for
            
            display = display   "\n"; //new line 
        } // end of outer for
           
    JOptionPane.showMessageDialog(null,"Values in Array\n"   display   "Lowest value is "   low, "Values in Array", JOptionPane.INFORMATION_MESSAGE);
    } // end of method
} // end of class

CodePudding user response:

Replace :

int low = a[i][j];

with :

int low = Integer.MAX_VALUE;

CodePudding user response:

// declaration of array
int a[][] = new int[3][3];

The issue is here, when you instantiate the array it automatically fills every emtry with 0, as this is the equivalent of the undefined value for an integer type. eg.

new int[3][3]
>> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Therefore your low variable always has the value 0 and is never replaced by something lower

CodePudding user response:

When you initialize an array implicitly in Java, the memory gets set to null, 0, 0L, 0.0f, false, or 0.0, etc, as appropriate for the datatype.

That means that your statement int low = a[i][j]; is setting low to an initial value of zero. All further comparisons will be against that, so your only chance to change that value is to enter a negative number, like -1.

You can add a test to your loop to initialize low with the first element of the loop you get:

if((i == 0 && j == 0) || a[i][j] < low)

Another option is to initialize low to the largest possible integer instead of implicit zero. In this simple example, that's probably the simplest approach to take:

int low = Integer.MAX_VALUE;

A third option is to add a boolean flag:

int low = ...;
boolean isFirst = true;

...

    if(isFirst || a[i][j] < low)
        ...
    isFirst = False;

CodePudding user response:

You have to input negative numbers for it to change. Otherwise, you can change it to

if(a[i][j] < low) 
    low = a[i][j];

but the name low wouldn't make sense anymore (it will be a "max").

  •  Tags:  
  • Related