Tory Davenport Tory Davenport - 7 months ago 23
Java Question

Formatting java text with void method

I have looked and cant find the information I am looking for. My code is functioning as I expect it to but I have one bit of code that I would like to improve.

The problem is that I can not call a void method within a print statement like this:

System.out.print("Water is a " + printTemp(temperature) + " at" + temperature + " degrees.";


printTemp(temperature is a void method so this won't work, as a result I found a work-around but it is not ideal:

System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");


here is the full code:

import java.util.Scanner;
public class printTemp {

public static void main(String[]args) {

Scanner input = new Scanner(System.in);
System.out.print("Please enter the temperature: ");
Double temperature = input.nextDouble();
// takes the state of the water from the printTemp method and
// the temperature to return a formatted output to the user
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");

}

public static void printTemp(double temperature) {
String returnMessage = "null" ;

if (temperature < 32 )
returnMessage = "solid";
else if (temperature > 212)
returnMessage = "gas";
else
returnMessage = "liquid";
System.out.printf(returnMessage);
}


}

This is for school thus there are conditions that must remain, printTemp MUST be a void method and the variable temp must remain a DOUBLE.

Answer

What about to put the following code snippet

...
System.out.print("Water is a " + returnMessage + " at" + temperature + " degrees.");

to the printTemp method as the last line? Then in the main outputs nothing and you just write:

...
printTemp(input.nextDouble());