Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting java text with void method

Tags:

java

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.

like image 429
Tory Davenport Avatar asked Jan 21 '26 06:01

Tory Davenport


1 Answers

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());
like image 91
Andrew Tobilko Avatar answered Jan 23 '26 18:01

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!