【问题标题】:Input Validation for GUIGUI 的输入验证
【发布时间】:2018-05-21 01:09:11
【问题描述】:

我的程序工作正常,我只需要在输入0a negative number 之后添加一个输入验证“无效输入,数字必须是正数”对话框,长度为:tLength 和宽度: tWidth

这是我运行良好的代码,只是需要添加验证

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

}

我试过了

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

我相信它收到了"Bad operand for binary operator '&lt;='". 的错误,因为tLengthtWidth 都是String

然后我尝试了

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;

当我将0negative number 放入 tLength 或 tWidth 字段时,它接受了它但没有更改输出。

所以最后我尝试了

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;

此外,没有错误,但在输入 negative numbers0 时不起作用。

我也尝试将'&amp;&amp;' 切换为'||',但没有成功。

【问题讨论】:

  • 肯定是||
  • 我将 && 切换到 ||在每条语句上,它都不起作用,我还尝试使用 JOptionPane 来显示错误消息,但它也不起作用。
  • 你说它不起作用是什么意思?你有打开控制台吗?你会在任何地方打印计算出的面积吗?
  • 我的意思是它没有输出“无效输入,数字必须是正数”,即使用户输入负数或0,它也会继续程序。跨度>
  • 嗯,你有

标签: java validation


【解决方案1】:

TL;DR,您需要第二个代码块。

你就快到了:

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

除了应该是||而不是 &&,问题是您正在尝试将 String 与 int 进行比较。为了使这项工作,您需要将字符串解析为整数,因此只需将字符串包装在 Integer.parseInt() 函数中。您的最终 if 语句应如下所示:

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

下一部分不是必需的,但有助于保持代码整洁:

因为花括号内只有1条语句,所以你实际上并不需要它们,所以你可以写和上面一样的东西,但是像这样:

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

任何以下代码行都将位于 if 语句代码块之外。

一个稍微复杂一点的例子: 如果是我,我会使用三元运算符并将结果分配给变量并像这样打印变量:

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

这基本上是几行代码合二为一。前两个词创建了“输出”变量。 “=”的RHS上的东西是三元运算。 三元运算只是一个 if 语句,它说 如果 "x" = true 则执行 A 否则做 B。

因此,如果 Integer.parseInt(tLength.getText())

希望对您有所帮助。

【讨论】:

  • 如果它需要是正数,但不一定是整数,那么不要使用 Integer.parseInt(),而是使用 Float.parseFloat() 或 Double.parseDouble()。如果你的值为 "0.1" 并尝试使用 Integer.parseInt("0.1") 你会得到一个异常。
  • 另外,如果您首先需要检查String是否真的是数字,那么您可以使用this post第三个答案中的方法
  • 我最终弄明白了,我不得不使用 JOptionPane。
  • 感谢您的回复和帮助!
【解决方案2】:

我最终使用了 JOptionPane 并使用了这个有效的代码。谢谢大家的帮助,我很感激。

 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;

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 1970-01-01
    • 2014-03-25
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多