字符串不等于字符串? [英] String is not equal to string?

查看:114
本文介绍了字符串不等于字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String[] letters  = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "L"};

Scanner inp = new Scanner(System.in);
String input = (inp.nextLine());
String[] cord = input.split("");

for(int x = 0; x < 10; x++)
    if(letters[x] == cord[1])
        System.out.println("Fk yeah!");

为什么 Fk是啊!如果我输入一个AL字母,就不会发生?

Why the Fk yeah! never happens if I input one of A-L letters?

推荐答案

字符串是对象。 == 按引用比较对象,而不是内部值。

Strings are objects. The == compares objects by reference, not by their internal value.

有两种解决方案:


  1. 使用 String#equals() 方法改为比较两个值 String objects。

  1. Use String#equals() method instead to compare the value of two String objects.

if (letters[x].equals(cord[1]))


  • 使用 char 而不是 String 。这是一个原始的,所以 == 将起作用。

  • Use char instead of String. It's a primitive, so == will work.

    char[] letters  = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L'};
    
    Scanner inp = new Scanner(System.in);
    String input = (inp.nextLine());
    char[] cord = input.toCharArray();
    
    for (int x = 0; x < 10; x++)
        if (letters[x] == cord[1])
            System.out.println("Fk yeah!");
    


  • 这篇关于字符串不等于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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