二进制的坏运算符类型>

时间:2015-08-06 10:25:55

标签: java compiler-errors

我正在尝试编写一个程序来排序三个数字。要求是在文本字段中输入三个数字。编译时我得到一个错误“二进制<”的错误运算符类型。可能与我试图从String中获取int有关,但无法解决它。我该如何解决?

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()
}        

}

1 个答案:

答案 0 :(得分:1)

您无法将字符串与>进行比较。您应该比较从字符串中获得的解析值(number1,number2,number3)。即,使用number1 > number2等......

另一种方法是使用input1.compareTo(input2)>0来比较String,但是这会给你字典顺序而不是数字顺序(如果所有String都有相同的字符数,你仍然会用字典顺序得到正确的结果。)