简体   繁体   English

如何将两个 for 循环的 Output 组合成“表格”格式?

[英]How do I combine an Output of two for loops into a “table” format?

I used two for loops to convert miles to km and km to miles respectively for selected values.对于选定的值,我使用两个 for 循环分别将英里转换为公里,将公里转换为英里。 However the issue I am facing is that the output for the first for loop is not side by side with the output of the second table.但是我面临的问题是第一个 for 循环的 output 与第二个表的 output 不并排。 Appreciate some help on this!感谢一些帮助!

public static double miletoKilometer(double mile) {
 double conversion = mile * 1.609;
 return conversion;
}

public static double kilometerToMile(double km) {
 double conversion2 = km / 1.609;
 return conversion2;
}

public static void main(String[] args) {
 int mileInput = 0;
 double kmOutput = 0;
 int kmInput = 0;
 double mileOutput = 0;
 int displayRow1 = 0;
 int displayRow2 = 0;
 System.out.print("Miles\tKilometres\tKilometres\tMiles \n");

 for (int i = 0; i < 11; i++) {
  if (i == 1 || i == 2 || i == 9 || i == 10) {
   mileInput = i;
   System.out.printf("\n" + i);
   kmOutput = miletoKilometer(mileInput);
   System.out.printf("\t %.3f\n", kmOutput);
  }
 }
 for (int j = 0; j < 66; j++) {
  if (j == 20 || j == 25 || j == 60 || j == 65) {
   kmInput = j;
   System.out.printf("\n\t\t         " + j);
   mileOutput = kilometerToMile(kmInput);
   System.out.printf("\t\t%.3f", mileOutput);
  }

 }
}

Current Output: enter image description here当前 Output:在此处输入图像描述

Changing your loop to match the code below should put everything in the right order.更改循环以匹配下面的代码应该将所有内容按正确的顺序排列。 Not the most elegant solution but it gets the job done.不是最优雅的解决方案,但它可以完成工作。

        int j = 0;
    for (int i = 0; i < 11; i++) {
        if (i == 1 || i == 2 || i == 9 || i == 10) {
           mileInput = i;
           System.out.printf("\n" + i);
           kmOutput = miletoKilometer(mileInput);
           System.out.printf("\t %.3f", kmOutput);
           for (; j < 66; j++) {
               if (j == 20 || j == 25 || j == 60 || j == 65) {
                 kmInput = j;
                 System.out.printf("\t\t         " + j);
                 mileOutput = kilometerToMile(kmInput);
                 System.out.printf("\t\t%.3f\n", mileOutput);
                 j++;
                 break;
              }
          }
        }
    }

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM