Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用简单的循环函数确保写在文本字段中的值相同?_Java_Loops_Jtextfield - Fatal编程技术网

Java 如何使用简单的循环函数确保写在文本字段中的值相同?

Java 如何使用简单的循环函数确保写在文本字段中的值相同?,java,loops,jtextfield,Java,Loops,Jtextfield,我编写了一个简单的代码来检查文本字段之间的值,并比较它们是否相同。我希望它们是一样的,否则会产生错误。这是关于重写一封电子邮件 String a = studentemail.getText(); String b = rewritestudentemail.getText(); if(a != b){ JOptionPane.showMessageDialog( null, "Student Email rewritten incorrectly."

我编写了一个简单的代码来检查文本字段之间的值,并比较它们是否相同。我希望它们是一样的,否则会产生错误。这是关于重写一封电子邮件

    String a = studentemail.getText();
    String b = rewritestudentemail.getText();

    if(a != b){
         JOptionPane.showMessageDialog( null, "Student Email rewritten incorrectly.","Error!",JOptionPane.OK_OPTION);

    }
即使我在两个字段中指示了相同的字符串值,程序仍会坚持存在错误。为什么会这样?

试试:

if (!a.equals(b)) {
   ...

将您的条件更改为:

if(!a.equals(b))
{
   JOptionPane.showMessageDialog( null, "Student Email rewritten
   incorrectly.","Error!",JOptionPane.OK_OPTION);
}

确保您拥有
在a.equals(b)之前,因为您只希望在它们不相等时出现错误。

而是像这样布局您的逻辑:

if (!a.equals(b)){
 //JoptionPane...
 }

在java中,使用“.equals()”函数比较两个字符串。

不要使用
==
比较字符串值。使用
equals()
,所以
!a、 在你的例子中等于(b)
。这个“!”工作得很好。谢谢你,eKek0!!:谢谢你回答我的问题!:D