1

I would like to have an array that contains strings with variable, so the user will be able choose which sentence he wants and what will be the value of the variable.

For example, the array will contain:

arr[0] = "Hi " + name + ", Welcome"
arr[1] = "Happy Birthday " + name;
arr[2] = "You are " + name;

I want to get an array like this from a function, and then to print it with some name. For example:

String s = (a[0], "Joe")

So that s will be:

Hi Joe, Welcome

Is it possible?

1
  • no in that way. You can have instead a array of Cheer that print something depending on the input Commented Dec 27, 2018 at 14:22

2 Answers 2

8

You could do:

String[] arr = new String[3];
arr[0] = "Hi %s, Welcome"
arr[1] = "Happy Birthday %s";
arr[2] = "You are %s";

Then

for (String s : arr) {
    System.out.printf(s + "%n", "Joe");
}

Which outputs:

Hi Joe, Welcome
Happy Birthday Joe
You are Joe

The printf uses the java.util.Formatter to allow insertion of variables into a String. The %n creates a new line within the Formatter

For more on this, please check out this relevant tutorial: Formatting Numeric Print Output

Sign up to request clarification or add additional context in comments.

4 Comments

Your code is not compilable. The %s phrases must be part of the string.
@Seelenvirtuose: dang, you're right! Thanks!! sloppy quick answer :(
@HovercraftFullOfEels is there any option that s will be the full string (like in the printing result), so that I can use him to something else?
Ok, I found it: String s2 = String.format(a[0], "Joe"); Thanks!
0

you can define an interface to Cheer and implement each behavior like this

interface Cheer {
    String cheerTo(String name);
}

class Welcome implements Cheer {

    @Override
    public String cheerTo(String name) {
        return "Hi " + name + ", Welcome";
    }
}

class Birthday implements Cheer {

    @Override
    public String cheerTo(String name) {
        return "Happy Birthday " + name;
    }
}

class Whoim implements Cheer {

    @Override
    public String cheerTo(String name) {
        return "You are " + name;
    }
}

then you can use it like this

    Cheer[] array = new Cheer[3];
    array[0] = new Welcome();
    array[1] = new Birthday();
    array[2] = new Whoim();

    String s = array[0].cheerTo("Joe");
    String b = array[1].cheerTo("Sam");
    System.out.println(s); // prints:  Hi Joe, Welcome 
    System.out.println(b); // prints:  Happy Birthday Sam

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.