0

Say, for example, I have a double variable in Java:

double alpha = 3;

However, I wanted to create a String variable, including that Double Variable:

String beta = "Alpha has a value of " + alpha;

So that the output would be

//Output
Alpha has the value of 3

However, it will not let me do so, as it says the double value cannot be included in the string value.

As I am doing this for around 150 variables, I want to know how to do it the simplest and shortest way.

Thanks

2
  • You should put variable names in lowercase. Commented Nov 16, 2014 at 13:18
  • Double.toString(double value) Commented Nov 16, 2014 at 13:20

3 Answers 3

4

I am doing this for around 150 variables

A common way of simplifying a repeated task is defining a helper method for it:

String description(String name, Object obj) {
    return name + " has a value of " + obj;
}

Now you can use it like this:

String beta = description("Alpha", alpha);

Doing this for 150 variables sounds suspicious - chances are, you have an opportunity to make an array. You can define an array of names, then pair them up with values, like this:

String[] names = new String[] {
    "Alpha", "Beta", "Gamma", ...
}
double[] values = new double[] {
    1.2, 3.4, 5.6, ...
}
for (int i = 0 ; i != names.length() ; i++) {
     System.out.println(description(names[i], values[i]));
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Double.toString(double).

String beta = "Alpha has a value of " + Double.toString(alpha);

Comments

1

When you need to convert a double to a string, use

Double.toString(double);

Where double is the name of the variable.

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.