【发布时间】:2013-11-28 09:28:47
【问题描述】:
我有两个类:Customer 和 MovieSeating。 (问题出现在 MovieSeating 中的 assignCustomerAt 方法中)
public class Customer
{
private String lastName;
private String firstName;
// This constructor sets the first name and last name to "???"
public Customer(){
lastName = "???";
firstName = "???";
}
// This method returns a string containing a customer's initials
// (first characters of firstName and lastName.)
public String toString()
{
String result = firstName.charAt(0) + "." + lastName.charAt(0) + ".";
return result;
}
}
所以something.toString(); 返回"?.?."
对吗?
一切都很好,但就是这样。
public class MovieSeating{
public Customer[][] seating;
public int rowNumber;
public int colNumber;
public MovieSeating(int rowNum, int columnNum){
rowNumber= rowNum;
colNumber=columnNum;
Customer thisGuy = new Customer();
Customer[][] seaTing = new Customer[rowNum][columnNum];
for(int i = 0; i<rowNum;i++){
for(int j = 0; j<columnNum; j++){
seaTing[i][j] = thisGuy;
}
}
seating = seaTing;
}
public boolean assignCustomerAt(int row, int col, Customer tempCustomer){
String a = seating[row][col].toString();
if(a=="?.?."){ //THE CONDITION IN THIS IF STATEMENT IS THE PROBLEM
seating[row][col] = tempCustomer;
return true;
}
return false;
}
最后一种方法的目的是当且仅当座位没有被占用时才将某人分配到一个位置(正如具有首字母“?.?.”的客户所指出的那样)。但无论如何,当 String a 的值为“?.?.”时,条件返回 false。我已经尝试并测试了 seat[row][col].toString();返回“?.?.”确实如此。我已经在每个项目周围加上括号,并尝试制作两个不同的字符串,这个和那个,没有任何效果!这就像说(1 * 1)!= 1。有什么关系????提前致谢
【问题讨论】:
-
一个很长的问题,但您应该使用
equals()方法来比较对象而不是==运算符。 -
为什么找不到类似字符串的人也找不到类似帖子? ;)