Martin Erlic
Martin Erlic

Reputation: 5665

How can I store strings with variables in them in another Java class?

I would like to store a series of "Strings" in a separate class (Constants.java) for organizational purposes.

Constants.java:

public static final String qualification1 = "'Priority' = \"" + priority + "\" AND 'Status' = \"In Progress\" AND 'Assignee' = \"" + assigneeInput + "\"";
...

In my main application class I would like to call these from from above

Main.java:

// Examples to show that these variables are dynamic
String assigneeInput = soapResponseAssignee.getSOAPBody().getTextContent();
String[] priorityList = {"Low", "Medium", "High", "Critical"};

for (String priority : priorityList) {
    String qualification = RemedyConstants.qualification1;
    String qualification = RemedyConstants.qualification2;
    String qualification = RemedyConstants.qualification3;
    ...
}

The problem is that the Strings provided to my Main class tend to have variables in them, i.e. priority or assigneeInput, which are defined there. If I store the strings elsewhere, i.e. Constants.java, I will not actually be using the Strings that I want. How can I provide the strings that I want while referencing those variables in their appropriate context?

Upvotes: 0

Views: 252

Answers (2)

Martin Erlic
Martin Erlic

Reputation: 5665

Quite simple. Not sure why it didn't click initially that I could treat the string as an object attribute...

Main.java:

String qualification = RemedyConstants.getQualification1(priority, assigneeInput);

Constants.java:

public static String getQualification1(String priority, String assigneeInput) {
        return "'Priority' = \"" + priority + "\" AND 'Status' = \"In Progress\" AND 'Assignee' = \"" + assigneeInput + "\"";
    }

Upvotes: 0

Ôrel
Ôrel

Reputation: 7622

Use String format

public static final String qualification1 = "'Priority' = \"%s\" AND 'Status' = \"In Progress\" AND 'Assignee' = \"%s\"";

Then when you want to use it

String.format(qualification1, "Low", "Alice");

Or add function into your class doing the format

String getQualification1(String priority, String assignee) {
    return String.format(qualification1, priority, assignee);
}

Upvotes: 2

Related Questions