再次使用java中的字符串比较 [英] String comparison in java, again

查看:100
本文介绍了再次使用java中的字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手问题,但我有这个代码:

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

我只需要打印当用户在询问时输入y时,再次显示欢迎消息。
但它没有用。任何想法?

I just need to simply print the welcome message again when user input "y" when asked. But it's not working. Any ideas?

推荐答案

在Java中,使用<比较基本类型(int,long,boolean等)的相等性code> == ,而使用 equals()方法比较Object types(String等)的相等性。如果你使用 == 比较两个对象类型,你要检查身份,而不是相等 - 也就是说,你要验证是否两个对象在内存中共享完全相同的引用(因此是同一个对象);一般来说,你需要的只是验证他们的是否相同,为此你使用 equals()

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. 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().

作为一个优秀的编程习惯,最好比较这样的字符串,翻转字符串的顺序:

As a good programming practice, it's better to compare Strings like this, flipping the order of the strings:

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

这样,你可以确定比较是有效的,即使 confirm 为null,也避免了潜在的 NullPointerException

In this way, you can be sure that the comparison will work, even if confirm was null, avoiding a potential NullPointerException.

这篇关于再次使用java中的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆