Search code examples
javaarraysjoptionpane

Comparing String Array


Good Eve guys, this is a school activity, and i find difficulty in comparing my INPUTTED ARRAY if it is equal to 0(ZERO), greater than 0(ZERO), and lesser than 0(ZERO).

heres my code...

String display="";

    String size = JOptionPane.showInputDialog("Enter Your Prefered Size Of Your Array");
    int newsize = Integer.parseInt(size);

    JOptionPane.showMessageDialog(null,"You Entered "+newsize+".");

    String array[] = new String[newsize];

    for (int a=0; a<array.length;a++)
    {
        array[a]=JOptionPane.showInputDialog("Enter Value For Array["+a+"].");

    }


    //i'm having trouble here.........

    for (int a=0;a<array.length;a++)
    {
        if (array[a].equals(array[0]))
        {

        }
        else if (array[a] < (array[0]))
        {

        }



        display=display+array[a]+"\n";
    }
    JOptionPane.showMessageDialog(null,"Arrays\n"+display);

please someone help me......

EDITTED:

and at the lastpart i want it to display that the ARRAY is "ZERO", "POSITIVE", "NEGATIVE" (i really dont know how to do it).


Solution

  • You can't use conditional operator < in String comparison. Use compareTo method.

     array[a].compareTo(array[0])> 0 // greater    
     array[a].compareTo(array[0])< 0 // less
     array[a].compareTo(array[0])== 0 // equals
    

    Update

    Update your code with following segments.

    for (int a=0;a<array.length;a++)
    {
        if (array[a].compareTo(array[0])== 0)
        {
          //this is equals block
        }
        else if (array[a].compareTo(array[0])< 0)
        {
         //this is less than block.
        }
        display=display+array[a]+"\n";
     }