可能重复:
Java string comparison?
我对Java很新,并且对我的if / else语句无法执行的原因有疑问。该方法的目标是基于从文本文件读入的符号加载2D阵列。符号将转换为数字以填充数组。据我所知,用于确定if或if / else语句是否应该执行的布尔逻辑是合理的,但它们都没有。谢谢你的帮助。
代码:
public void loadText(Scanner sc) {
for (int row = 1; row <= grid.length; row++) {
for (int col = 1; col <= grid[row].length; col++) {
String x = sc.next();
if ((x == " ") && (row <= 10)) {
grid[row][col] = 0;
} else if ((x == "*") && (row <= 10)) {
grid[row][col] = 1;
} else if ((x == "$") && (row <= 10)) {
Arrays.fill(grid[row], 0);
} else if (row >= 11) {
break;
}
}
答案 0 :(得分:7)
使用.equals
或.equalsIgnoreCase
比较字符串。
答案 1 :(得分:6)
比较字符串时使用
是一种很好的做法" ".equals(x) in stead of x == " "
答案 2 :(得分:5)
对于字符串比较代码,您需要将==替换为.equals(),例如
if (" ".equals(x) && (row <=10)) {
}
==检查两个对象是否是同一个对象,equals()方法检查它们是否代表同一个对象。在Java中,equals()可以被类重写以做正确的事情,但==不能。
答案 3 :(得分:3)
双等号符号比较任何非原始的地址。
由于String是类的实例,您应该使用这样的equals方法
for (int row = 1; row <= grid.length; row++) {
for (int col = 1; col <= grid[row].length; col++) {
String x = sc.next();
if ((x.equals(" ")) && (row <= 10)) {
grid[row][col] = 0;
} else if ((x.equals("*")) && (row <= 10)) {
grid[row][col] = 1;
} else if ((x.equals("$")) && (row <= 10)) {
Arrays.fill(grid[row], 0);
} else if (row >= 11) {
break;
}
}
答案 4 :(得分:-1)
如果符号为单个字符,您可以使用char
数据类型代替String
x
来完成工作
(x == '$') && (row <= 10)
答案 5 :(得分:-1)
我认为以上所有答案都得出结论,是的我同意大多数答案,但你的问题是你不知道x是什么。
您需要将其注销,但尝试添加一行
System.out.println(x);
You will see what is being compared.
A test shows what you have could work;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class BooleanLogicTest {
@Test
public void testLogical() {
String x = " ";
boolean result = x == " ";
assertTrue("Could be true", result);
}
@Test
public void testCompare() {
String x = " ";
boolean result = " ".equals(x);
assertTrue("Could be true", result);
}
@Test
public void testLogicalX() {
String x = "*";
boolean result = x == "*";
assertTrue("Could be true", result);
}
@Test
public void testCompareX() {
String x = "*";
boolean result = "*".equals(x);
assertTrue("Could be true", result);
System.out.println(x);
}
}