简体   繁体   English

再次使用java中的字符串比较

[英]String comparison in java, again

Newbie question, but I have this code: 新手问题,但我有这个代码:

import java.util.*;
import java.io.*;

public class Welcome1  
{
   // main method begins execution of Java application
   public static void main( String[] args )
   {
      String confirm = "y";
      while(confirm=="y")
      {
         System.out.println( "Welcome to Java Programming!" );
         System.out.println( "Print Again? (y/n)" );
         Scanner input = new Scanner(System.in);
         confirm = input.nextLine();
      }
   }
}

I just need to simply print the welcome message again when user input "y" when asked. 我只需要在用户输入“y”时再次打印欢迎信息。 But it's not working. 但它不起作用。 Any ideas? 有任何想法吗?

In Java, the primitive types (int, long, boolean, etc.) are compared for equality using == , whereas the Object types (String, etc.) are compared for equality using the equals() method. 在Java中,使用==比较基本类型(int,long,boolean等)的相等性,而使用equals()方法比较Object类型(String等)的equals() If you compare two Objects types using == , you're checking for identity , not equality - that is, you'd be verifying if the two objects share exactly the same reference in memory (and hence are the same object); 如果使用==比较两个对象类型,则需要检查标识 ,而不是相等 - 也就是说,您将验证两个对象是否在内存中共享完全相同的引用(因此是相同的对象); and in general, what you need is just verifying if their values are the same, and for that you use equals() . 一般来说,你需要的只是验证它们的是否相同,为此你使用equals()

As a good programming practice, it's better to compare Strings like this, flipping the order of the strings: 作为一个很好的编程实践,最好比较这样的字符串,翻转字符串的顺序:

while ("y".equals(confirm)) {

In this way, you can be sure that the comparison will work, even if confirm was null, avoiding a potential NullPointerException . 通过这种方式,您可以确保比较将起作用,即使confirm为null,也避免了潜在的NullPointerException

对于字符串比较,请使用.equals()。

while(confirm.equals("y")){

you should use equals() instead of operator==. 你应该使用equals()而不是operator ==。

the operator== checks if the two object are actually the same objects, while you want to check if they are equal. operator ==检查两个对象是否实际上是同一个对象,而你想检查它们是否相等。

code snap: 代码快照:

while(confirm.equals("y")) {

Rewrite your code as follows (just an example): 重写你的代码如下(只是一个例子):

import java.util.*;
import java.io.*;

public class Welcome1 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String confirm = "y";

        do {
            System.out.println("Welcome to Java Programming!");
            System.out.println("Print Again? (y/n)");
            confirm = input.nextLine();
        }
        while (confirm.equalsIgnoreCase("y"));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM