1

My program works fine as is, I just need to add an input validation "invalid input, number has to be positive" dialog, after an input of 0 or a negative number for length: tLength and width: tWidth.

Here is my code which runs fine, just needs the validation added:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class FloorsRUs extends JFrame implements ActionListener, ItemListener 
{

    public JTabbedPane jTP;
    public JRadioButton flrWood = null;
    public JRadioButton flrCarpet = null;
    public JTextField tCName;
    public JTextField tAddress;
    public JTextField tLength;
    public JTextField tWidth;
    public JButton calcArea; 
    public JButton calcCost;
    public JButton subOrder;
    public JButton orderSum;
    public JButton ordList;
    public JPanel flrPan; 
    public JPanel lwPan;
    public JPanel cPan;
    public JLabel lab1;
    public JLabel lab2;
    public JLabel lab3;
    public JLabel lab4;
    public String flrType;
    public double area = 0;
    public double cost = 0;


    FloorsRUs(String title)
    {
        super(title);
        jTP=new JTabbedPane();
        flrPan=new JPanel();
        lwPan=new JPanel();
        cPan=new JPanel();

        flrPan.add(flrWood=new JRadioButton("Choose Wood"));
        flrPan.add(flrCarpet=new JRadioButton("Choose Carpet"));

        ButtonGroup grp = new ButtonGroup();
        grp.add(flrWood);
        grp.add(flrCarpet);

        lwPan.add(lab1=new JLabel("Enter the Length : "));
        lwPan.add(tLength=new JTextField(10));

        lwPan.add(lab2=new JLabel("Enter the Width"));
        lwPan.add(tWidth=new JTextField(10));

        lwPan.add(calcArea=new JButton("Calculate the Area"));
        lwPan.add(calcCost=new JButton("Calculate the Cost"));
        lwPan.add(subOrder=new JButton("Submit the Order"));

        cPan.add(lab3=new JLabel("Enter the Customers Name : "));
        cPan.add(tCName=new JTextField(10));

        cPan.add(lab4=new JLabel("Enter the Customers Address : "));
        cPan.add(tAddress=new JTextField(10));

        cPan.add(orderSum=new JButton("The Order Summary"));
        cPan.add(ordList=new JButton("The Order List"));

        jTP.addTab("Select Floor Type ",flrPan);
        jTP.addTab("Enter Length and Width ",lwPan);
        jTP.addTab("Customer Info",cPan);
        add(jTP);

        calcArea.addActionListener(this);
        calcCost.addActionListener(this);
        subOrder.addActionListener(this);  
        orderSum.addActionListener(this);
        ordList.addActionListener(this);
        flrWood.addItemListener(this);
        flrCarpet.addItemListener(this);


    }
    @Override
    public void itemStateChanged(ItemEvent ie)

    {
        if(flrWood.isSelected()){
            flrType="Wood";

        }

        else if(flrCarpet.isSelected()){
            flrType="Carpet"; 
        }

    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {

        String source=ae.getActionCommand();

        switch (source) {

        case "Calculate the Area":
            System.out.println("Calc 1 Complete");
            area=Double.parseDouble(tLength.getText())
            *Double.parseDouble(tWidth.getText());
            break;

        case "Calculate the Cost":
            System.out.println("Calc 2 Complete");
            if(flrType.equals("Wood"))
            cost = area *20;
            else if(flrType.equals("Carpet"))
            cost = area *10;
            break;

        case "The Order Summary":
            JOptionPane.showMessageDialog(null,"The Order Summary - Area is :" + 
            ""+area+""+ " The Cost is :  "+cost," Information",
            JOptionPane.INFORMATION_MESSAGE);
            break;

        case "The Order List":
            JOptionPane.showMessageDialog(null,"The Order List : \n Customer's name : 
"+tCName.getText()
            +"\nAddress : "+tAddress.getText()
            +"\n The Area is :"+area
            +"\n The Cost is : "+cost,"Information",
            JOptionPane.INFORMATION_MESSAGE);
            break;

        default:

            break;
        }



    }  

    public static void main(String args[])

    {
        FloorsRUs f1=new FloorsRUs("FloorsRUs Easy App");
        f1.setSize(new Dimension(650,450));
        f1.setVisible(true);
    }

}

I've tried:

if(tLength.getText()<=0 && tWidth.getText()<=0)
{
    System.out.println("invalid input, number has to be positive");
}

And it received errors for "Bad operand for binary operator '<='". I believe because tLength and tWidth are both String.

So then I tried:

case "Calculate the Area":
System.out.println("Calc 1 Complete");
area=Double.parseDouble(tLength.getText())
*Double.parseDouble(tWidth.getText());
if((Double.parseDouble(tLength.getText())<=0) && 
((Double.parseDouble(tWidth.getText())<=0)))
{
   System.out.println("invalid input, number has to be positive");
}
break;

It accepted it but didn't change the output when I put a 0 or negative number into the tLength or tWidth field.

So finally I tried:

case "Calculate the Area":
        System.out.println("Calc 1 Complete");
        try {
            if ((Double.parseDouble(tLength.getText()) < 0)
                    && ((Double.parseDouble(tWidth.getText()) < 0))) {
                System.out.println("invalid input, number has to be 
positive");
            } else {
                area = Double.parseDouble(tLength.getText()) * 
Double.parseDouble(tWidth.getText());
            }

        } catch (NumberFormatException e) {
            System.out.println("invalid input, number has to be positive");
        }
        break;

Also, no errors but it didn't work when negative numbers or 0 were entered.

I have tried switching '&&' to '||' as well and no luck.

halfer
  • 19,824
  • 17
  • 99
  • 186
SnipeFX
  • 11
  • 4
  • It definitely has to be `||`. – Stefan Reich Dec 07 '17 at 02:00
  • I switched && to || on each statement and it didn't work, I also tried using a JOptionPane to display an error message and that as well didn't work. – SnipeFX Dec 07 '17 at 02:02
  • What do you mean it doesn't work? Do you have a console open? Do you print your calculated area anywhere? – Stefan Reich Dec 07 '17 at 02:04
  • What I mean is it didn't output "invalid input, number has to be positive", It just goes on with the program even if a negative number or 0 is entered by the user. – SnipeFX Dec 07 '17 at 02:07
  • Well, you have < 0 instead of <= 0, so if you enter 0, there will be no message. – Stefan Reich Dec 07 '17 at 02:08
  • True, but it still doesn't output for a negative number regardless so I don't know if that would make much difference. – SnipeFX Dec 07 '17 at 02:11
  • You might want to update the code to the (partially) fixed version. Are you sure the case block is even executed? – Stefan Reich Dec 07 '17 at 02:13
  • I changed the code to the partially fixed version, Wouldn't it give me at least a warning if it weren't executed? I'm using NetBeans. – SnipeFX Dec 07 '17 at 02:24
  • Does it print "Calc 1 complete"? Anyway I think this is almost solved – Stefan Reich Dec 07 '17 at 15:52
  • I figured it out and posted the answer here. It prints calc 1 complete and input validation using a JOptionPane. – SnipeFX Dec 07 '17 at 19:14

2 Answers2

0

TL;DR, the second code block is what you need.

You are almost there with this:

if(tLength.getText()<=0 && tWidth.getText()<=0)
{
    System.out.println("invalid input, number has to be positive");
}

Aside from the fact that it should be || and not &&, the problem is you are trying to compare a String to an int. To make this work, you need to parse the String as an integer, so just wrap up your string in the Integer.parseInt() function. Your final if statement should look like this:

if (Integer.parseInt(tLength.getText()) <= 0 ||
    Integer.parseInt(tWidth.getText()) <=0 )
{
    System.out.println("invalid input, number has to be positive");
}

This next part isn't necessary but helps keep code neat:

Because it is only 1 single statement inside the curly braces, you don't actually need them, so you can write the same thing as above, but like this:

if (Integer.parseInt(tLength.getText()) <= 0 ||
    Integer.parseInt(tWidth.getText()) <=0 )
        System.out.println("invalid input, number has to be positive");

Any following lines of code will be outside the if statement code block.

A slightly more complex example: If it were me, I would use the ternary operator and assign the result to the variable and print the variable like this:

String output = Integer.parseInt(tLength.getText()) <= 0 ||
                Integer.parseInt(tWidth.getText()) <= 0 ? 
               "invalid input, number has to be positive" : "";
System.out.println(output);

This is basically a few lines of code rolled into one. The first two words creates the 'output' variable. The thing on the RHS of the "=" is a ternary operation. A ternary operation is just an if statement that says If "x" = true then do A else do B.

So if Integer.parseInt(tLength.getText()) <= 0 is true then the string "invalid input, number has to be positive" will be assigned to the variable 'output'. But if Integer.parseInt(tLength.getText()) <= 0 is false then the string "" (an empty string) will be assigned to 'output'. This particular ternary operation also performs the same test on Integer.parseInt(tWidth.getText()), so if either of them are true, then the first option is used. The last line prints the contents of 'output' and places the cursor on the next line. This means if the empty string is printed, then the cursor will still move to the next line, but it won't print anything. Moving the cursor to the next line may or may not be what you want to do (if you don't, you can always use System.out.print() instead of System.out.println()).

Hope that helps.

Roclemir
  • 126
  • 2
  • 14
  • If it needs to be a positive, but not necessarily an integer, then instead of using Integer.parseInt(), use Float.parseFloat() or Double.parseDouble(). If you have a value of "0.1" and try to use Integer.parseInt("0.1") you will get an Exception. – Roclemir Dec 07 '17 at 03:55
  • Also, if you first need to check if the String is actually a number, then you can use the method in the third answer of [this post](https://stackoverflow.com/questions/14206768/how-to-check-if-a-string-is-numeric) – Roclemir Dec 07 '17 at 04:00
  • I ended up figuring it out, I had to use a JOptionPane. – SnipeFX Dec 07 '17 at 05:33
  • Thank you though for responding and helping! – SnipeFX Dec 07 '17 at 05:37
0

I ended up using a JOptionPane and used this code which worked. Thank you all for the help though, I appreciate it.

 String source = ae.getActionCommand();
    switch (source) {
        case "Calculate the Area":
            System.out.println("Calc 1 Complete");
            try {
                if ((Double.parseDouble(tLength.getText()) <= 0)
                        || ((Double.parseDouble(tWidth.getText()) <= 0))) {
                    JOptionPane.showMessageDialog(null, "invalid input, 
             number has to be positive", "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    area = Double.parseDouble(tLength.getText()) * 
                           Double.parseDouble(tWidth.getText());
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "invalid input, number 
                 has to be positive", "Error", JOptionPane.ERROR_MESSAGE);
            }
            break;

        case "Calculate the Cost":
            System.out.println("Calc 2 Complete");
            if (flrType.equals("Wood")) {
                cost = area * 20;
            } else if (flrType.equals("Carpet")) {
                cost = area * 10;
            }
            break;
SnipeFX
  • 11
  • 4