Home > Enterprise >  Editing a String phrase using int variables
Editing a String phrase using int variables

Time:09-24

Basically I am trying to display a phrase but with the A and B elements replaced with variables feet and inches. I know that Integer.parseInt can be used to accomplish this, but how would it work with a phrase?

For example:

public class EngLength {
    private int feet;
    private int inches;
    private String lengthValue = "A ft, B in";

    public EngLength(int feet, int inches) {
        this.feet = feet;
        this.inches = inches;
    }

    public String toString() {
        return this.lengthValue;
    }
}

CodePudding user response:

If I get it correctly, you can try something like

public String toString() {
    return lengthValue.replace("A", Integer.toString(feet)).replace("B", Integer.toString(inches));
}

Or, as suggested by tgdavies, by using String.format

public String toString() {
    return String.format("%d ft, %d in", feet, inches);
}

CodePudding user response:

You can try with initializing the lengthvalue in the constructor, when assigning the other 2 values.

public class EngLength {
    private int feet;
    private int inches;
    private String lengthValue;

    public EngLength(int feet, int inches) {
        this.feet = feet;
        this.inches = inches;
        //lengthValue = feet   " ft, "   inches   " in";
        //or
        //lengthValue = String.format("%d ft, %d in", feet, inches);
    }

    public String toString() {
        return this.lengthValue;
    }
}
  • Related