Jannes
Jannes

Reputation: 15

bad operator types for binary >

Am trying to write a program to sort three numbers. Requirement is the three numbers are entered in a textfield. When compiling I get an error "bad operator types for binary <". Probably has something to do with me trying to get the int from a String, but can't solve it. How do I fixe it?

public class Oef0502 extends JFrame {
public static void main( String[] args ) {
    JFrame frame = new Oef0502();
    frame.setSize( 400,200 );
    frame.setLocation( 400,200);
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    frame.setContentPane( new Panel() );       
    frame.setVisible( true );
}
static class Panel extends JPanel {
   private JTextField number1Field,number2Field,number3Field;
   public Panel() {
        ActionListener listener = new FieldHandler();

        number1Field = new JTextField( 10 );
        number1Field.addActionListener( listener );

        number2Field = new JTextField( 10 );
        number2Field.addActionListener( listener );

        number3Field = new JTextField( 10 );
        number3Field.addActionListener( listener );

        add( number1Field );
        add( number2Field );
        add( number3Field );
   }
   class FieldHandler implements ActionListener {
       public void actionPerformed( ActionEvent e) {
         String input1 = number1Field.getText();
         int number1 = Integer.parseInt( input1 );
         String input2 = number1Field.getText();
         int number2 = Integer.parseInt( input2 );
         String input3 = number1Field.getText();
         int number3 = Integer.parseInt( input3 );
         if (  input1  > input2  ) {
          int temp = input1;
          input1 = input2;
          input2 = temp; 
         }
         if ( input2 > input3 ) {
          int temp = input2;
          input2 = input3;
          input3 = temp;
         }
         if ( input1 > input2 ) {
          int temp = input1;
          input1 = input2;
          input2 = temp;
         }
       }
   }
 //line for giving the line back to the screen using paintComponent()
}        

}

Upvotes: 1

Views: 118

Answers (1)

Eran
Eran

Reputation: 394116

You can't compare Strings with >. You should compare the parsed values you get from your Strings (number1, number2, number3). I.e., use number1 > number2, etc...

An alternative is to use input1.compareTo(input2)>0 to compare the Strings, but that would give you lexicographical order and not numeric order (if all the Strings have the same number of characters, you'll still get the correct result with lexicographic order).

Upvotes: 1

Related Questions