我已查找並找不到要查找的信息。我的代碼正如我所期望的那樣工作,但我有一點我想要改進的代碼。使用void方法格式化java文本
的問題是,我不能像這樣的打印語句中調用一個void方法:
System.out.print("Water is a " + printTemp(temperature) + " at" + temperature + " degrees.";
printTemp(溫度是一個void方法,以便這不會工作,結果我發現了一個工作-around但它並不理想:
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");
這裏是全碼:
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);
}
}
這是學校因此有條件必須保持,printTemp必須是一個無效的方法和變量溫度必須保持一個DOUBLE。
沒有什麼你可以用這些約束做。那麼,除了將3種打印語句合併爲一個:'printf(「at%.0f degrees。%n」,temperature);' – Andreas
我真的不喜歡這樣的問題:「如果沒有我的學校作業,我該如何做X使用推薦和最乾淨的方式來做到這一點?「 – Dici
我不喜歡在論壇上發帖,但我不確定是否有更好的方法。感謝您幫助我學習! –