I'm trying to compare two variables that is being inputed by the user but then it wont function

if (txt_pay.getItem() < txt_amount.getItem())
{
   jOptionPane1.showMessageDialog(this, "please enter the right amount");
}

what could be wrong?

the error says

operator < cannot be applied to java.lang.string

another one is when there is no value it will say please input a number.

if (txt_pay.getItem().isEmpty())
{
   jOptionPane1.showMessageDialog(this, "please enter the right amount");
}

or

if (txt_pay.getItem() = NULL)
{
   jOptionPane1.showMessageDialog(this, "please enter the right amount");
}

i'm trying those code to put it in here but unluckily it wont function.

if (txt_pay.getText()!= "")
        {
            double iChange =  Double.valueOf(txt_pay.getText()) - Double.valueOf(txt_amount.getText());
            txt_change.setText(String.valueOf(iChange));
            jOptionPane1.showMessageDialog(this, "Your Change will be given to you with your order!. Thank you for using our system");
            this.hide();
        }

    

            String[] tableColumnsName = {"ID","Item","Price","Qty"};
            DefaultTableModel aModel = (DefaultTableModel) jTable1.getModel();
            aModel.setColumnIdentifiers(tableColumnsName);
            
            ResultSet rs =globals.executeQry("select id,item,price,qty from tblorders where cabin='" +
                    globals.cabin + "' and seatnum1='" + globals.seatnum1 + "' and seatnum2='" + globals.seatnum2 + "'");
try
{
            // Loop through the ResultSet and transfer in the Model
            java.sql.ResultSetMetaData rsmd = rs.getMetaData();
            int colNo = rsmd.getColumnCount();
            while(rs.next()){
             Object[] objects = new Object[colNo];
             // tanks to umit ozkan for the bug fix!
             for(int i=0;i<colNo;i++){
              objects[i]=rs.getObject(i+1);
              }
             aModel.addRow(objects);
            }
            jTable1.setModel(aModel);

            NumberFormat formatter = NumberFormat.getCurrencyInstance();
            formatter.setMaximumFractionDigits(2);
            //Double iTotal=0.00;
            for (int i=0;i<=(jTable1.getRowCount()-1);i++)
            {
                globals.executesqlcom("update tblinventory set itemcount= itemcount -" + jTable1.getValueAt(i, 3).toString() +
                        " where itemname='" + jTable1.getValueAt(i, 1).toString() + "'");
                
            }
}
 catch(Exception ex)
        {
            ex.printStackTrace();
        }

hope someone could help me... thanks in advance!

Dani AI

Generated

Good call by — Java will not let you use relational operators on String values. A safer, pragmatic pattern is:

  • ensure you are reading the right component value (JTextField uses getText(), JComboBox uses getSelectedItem() and usually needs a cast),
  • validate the text (check for null/blank before calling methods),
  • parse to a numeric type and handle bad input with a catch, and
  • for money use a decimal type that avoids floating-point rounding.

A compact, robust approach using BigDecimal (recommended for currency) looks like this:

String paidText = txtPay.getText();
String amountText = txtAmount.getText();

if (paidText == null || paidText.trim().length() == 0) {
    JOptionPane.showMessageDialog(this, "Please enter the payment amount");
    return;
}

try {
    java.math.BigDecimal paid = new java.math.BigDecimal(paidText.trim());
    java.math.BigDecimal amount = new java.math.BigDecimal(amountText.trim());

    if (paid.compareTo(amount) < 0) {
        JOptionPane.showMessageDialog(this, "Please enter the right amount");
        return;
    }

    java.math.BigDecimal change = paid.subtract(amount).setScale(2, java.math.RoundingMode.HALF_UP);
    txtChange.setText(change.toPlainString());
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(this, "Enter a valid numeric amount");
}

UI tips: use a JFormattedTextField, an InputVerifier or a DocumentFilter to block invalid characters as the user types. That reduces parse errors and improves UX. Also avoid calling methods on a possible null reference — check for null first. For currency math, prefer BigDecimal over double to avoid subtle rounding errors.

For details on BigDecimal behavior and methods used above see the BigDecimal javadoc: BigDecimal javadoc. This complements 's input and should make the validation/comparison reliable for 's form.

Recommended Answers

All 2 Replies

The first error is easy. You cannot compare String using this: "<". For Strings you need to use this function:

if (  txt_pay.getItem().compareTo(txt_amount.getItem())<0  )
{
   jOptionPane1.showMessageDialog(this, "please enter the right amount");
}

And when you do this:

if (txt_pay.getItem().isEmpty())

The method isEmpty() needs to return a boolean value.

Also in java the 'null' value is this null

if (txt_pay.getItem() == null) // 2 '=' symbols when comparing

Also use this '==' when comparing a String with a null value like above, but if you want to compare 2 Strings that have value use this:

if ( !txt_pay.getText().equals("")  )

Also this converts a String into a numer

String s1  = "22.22";
double d = Double.parseDouble(s1);

String s2  = "13";
int i = Integer.parseInt(s2);
commented: fantastic! he's a great help +3

got it! thanks for the help! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.