【问题标题】:if statement not working out for me - Java [duplicate]如果语句不适合我-Java [重复]
【发布时间】: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() 方法来比较对象而不是== 运算符。
  • 为什么找不到类似字符串的人也找不到类似帖子? ;)

标签: java logic


【解决方案1】:

无法使用== 比较字符串,因为您正在比较Object reference 而不是object information

你必须改成

a.equals("?.?."){

【讨论】:

    【解决方案2】:

    if(a=="?.?."){ 应该是if("?.?.".equals(a)) {

    【讨论】:

    • 谢谢!抱歉,解决方案如此简单。你能解释一下为什么会这样吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2021-04-27
    • 2017-12-02
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多