Home > OS >  Can't figure out how to return a string composed of two variables, a string and a integer?- rep
Can't figure out how to return a string composed of two variables, a string and a integer?- rep

Time:05-28

This program is using a get/set method for both, but I just can't figure out how!

Thanks to a helpful user recommending string.valueOf, I now have this

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".

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;
    }
}

CodePudding user response:

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.

  • public int getSeatNumber() <-- need to return an int type.
  • public String getSeatNumber() should work without throwing errors.

CodePudding user response:

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.

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).

  •  Tags:  
  • java
  • Related