有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在一个while循环中格式化它,使其打印为四列?

我需要把它分成四列

 public class Lab7aCelsiustoFahrenheit
    {
       public static void main(String[] args)
       {
        //variables
       double orig = -40.0;
       double cels = orig;
       double fahr = cels;
       final int MAX_TEMP = -1;      
         //loop that prints asingle column on celsius to F conversions
         while(cels <= MAX_TEMP)
         {
            System.out.println(cels + "C " + "is " + fahr + "F" + "\t");
            cels++;
            fahr = (((9.0 * cels) + 160) / 5);

            }

     }    
    }

共 (1) 个答案

  1. # 1 楼答案

    您可以在4个条目后换行,计算您写入的项目数,然后从下一行开始

    此外,为了使每个“单元”位于另一个单元的下方,您应该使用System.out.printf来编写条目,以格式化double-值

    如果您确实希望在单个while循环中执行此操作,则可能是:

    int column = 1;
    
    while(cels <= MAX_TEMP) {
        fahr = (((9.0 * cels) + 160) / 5);
    
        System.out.printf("%8.2fC is %8.2fF" + "\t", cels, fahr);
        cels++;
        column++;
    
        if(column > 4) {
            column = 1;
            System.out.println();
        }
    }
    

    我认为你也应该在系统运行之前进行计算。出来printf(…)