简体   繁体   English

不知道如何返回由两个变量组成的字符串,一个字符串和一个整数?-重新发布,更新

[英]Can't figure out how to return a string composed of two variables, a string and a integer?- repost, updated

This program is using a get/set method for both, but I just can't figure out how!该程序对两者都使用了 get/set 方法,但我就是不知道怎么做!

Thanks to a helpful user recommending string.valueOf, I now have this感谢有帮助的用户推荐 string.valueOf,我现在有了这个

public int getSeatNumber() {
    String output = "" + seatLetter + String.valueOf(seatNumber);
    return output;
}

but it still has the same error,但它仍然有同样的错误,

"Incompatible types, string cannot be converted to an int". “不兼容的类型,字符串无法转换为 int”。

Here is the full object, although not all variables are set, as this is recycled code.这是完整的对象,虽然没有设置所有变量,因为这是回收代码。

public class Ticket {

    private int seatNumber, phoneNumber;
    private double price;
    private String seatLetter, name;

    //default constructor
    public Ticket() {
        price = 300;
        seatNumber = 1;
        name = "John Doe";
        seatLetter = "A";
        
    }
    public double getPrice() {
      return price;
    }

    public int getSeatNumber() {
        String output = "" + seatLetter + String.valueOf(seatNumber);
        return output;
    }

    public String getModel() {
        return model;
    }

    public void setPrice(double _price) {
        price = _price;
    }

    public void setSeatNumber(int _seatNumber) {
        seatNumber = _seatNumber;
    }

    public void setSeatName(String _seatLetter) {
        seatLetter = _seatLetter;
    }

    @Override
    public String toString() {
        String output = "";
        output += "Model = " + model + "\n";
        output += "Price = $" + price + "\n";
        output += "Horsepower = " + horsePower + "HP";
        return output;
    }
}

You've declared a data type of String output and returning a string when the method is completed, but if you take a closer look at your method declaration, it is declaring that your method will return an int.您已经声明了 String 输出的数据类型并在方法完成时返回一个字符串,但是如果您仔细查看您的方法声明,它声明您的方法将返回一个 int。

  • public int getSeatNumber() <-- need to return an int type. public int getSeatNumber() <-- 需要返回一个 int 类型。
  • public String getSeatNumber() should work without throwing errors. public String getSeatNumber()应该可以正常工作而不会引发错误。

Change your method to this:将您的方法更改为:

public String getSeatNumber() {

    String output = "" + seatLetter + String.valueOf(seatNumber);

    return output; 
}

Notice how I changed the method return type to String .请注意我如何将方法返回类型更改为String

I advice you use String.format instead, as it will make your code cleaner (I didn't use it since I don't know the types of your values).我建议您改用String.format ,因为它会使您的代码更清晰(我没有使用它,因为我不知道您的值的类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM