在输出打印行中包括输入

Include input in output print line

提问人:Rs2023 提问时间:8/29/2023 更新时间:8/29/2023 访问量:30

问:

我正在尝试让我的代码将结果打印为“21.0 C = 69.80 F”,但我无法让它包含初始摄氏输入或将其限制为没有错误代码的第二个小数点。这是为了家庭作业,所以我想知道我哪里出了问题,以及我需要添加或删除什么才能格式化我的 System.out.print

public class Celcius2Farenheit {

        /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double celsius, fahrenheit;
        Scanner scanner;
        scanner = new Scanner(System.in);
        System.out.println("Please enter a temperature in celsius:");
        celsius = scanner.nextDouble();
        fahrenheit = (9.0 / 5.0) * celsius + 32;
        System.out.printf("%.2f"  + fahrenheit);
        
    }
    
}
格式 java.util.scanner

评论

2赞 MadProgrammer 8/29/2023
System.out.printf("%.2f C= %.2f F", celsius, fahrenheit);?

答:

0赞 Shila Mosammami 8/29/2023 #1

使用格式化方法,您走在正确的轨道上。但是,您提供给的格式字符串不完整。printfprintf

该方法允许您在格式字符串中指定占位符,然后提供参数来替换这些占位符。printf

下面介绍如何修改代码以获得所需的输出:

  1. 格式字符串应为:"%.2f C = %.2f F\n"
  2. 同时提供 和 作为参数。celsiusfahrenheitprintf

下面是代码的更正部分:

import java.util.Scanner;

public class Celcius2Farenheit {

    public static void main(String[] args) {
        double celsius, fahrenheit;
        Scanner scanner;
        scanner = new Scanner(System.in);
        System.out.println("Please enter a temperature in celsius:");
        celsius = scanner.nextDouble();
        fahrenheit = (9.0 / 5.0) * celsius + 32;
        System.out.printf("%.2f C = %.2f F\n", celsius, fahrenheit);
    }
    
}

现在,如果您输入类似 的值,它将正确打印: 。2121.00 C = 69.80 F