2015-09-05 51 views
0

您好,StackOverflow这是我的第一篇文章,所以我很抱歉,如果这种格式是搞砸了。我的指示是:编写一个名为DistanceVoid的类,其中包含void方法距离,如下所示。当在main方法的循环中重复调用时,这一个方法(本身)应该生成与上面的程序1所显示的完全相同的表。我会把图像,但它不会让我。这是我的代码。无效方法将英里数转换为公里/公里数千英里

package bryant6; 


public class DistanceVoid { 

    public static void main(String[] args) { 
     distance(0); 
    } 

    public static void distance(double dist) { 

     System.out.println(" Miles Kilometers - Kilometers Miles"); 
     System.out.println("-------------------------------------------------"); 
     int counter = 0; 
     int distanceCounter = 0; 
     while (counter < 10) { 
      counter++; 
      dist++; 
      distanceCounter++; 
      dist = distanceCounter * 1.609; 
      System.out.print(counter + " "); 
      System.out.println(dist); 

     } 

    } 
} 

我已经做了大量的研究,并试图照顾这一点,我张贴在我的课堂论坛没有答复。任何方向都会有帮助。 我还需要能够在这个代码中打印公里到英里,我打电话给。任何关于如何使代码更清洁和更好的建议也将被赞赏!

下面是结果应该是什么 http://imgur.com/H9HuTye

+1

我不明白这么好,他们应该怎么做这个节目.. –

+1

,你有什么确切的问题? –

+0

我会输出什么结果应该看起来像我无法获得图像链接工作 –

回答

1

我不知道你在写什么,因为我将自己的解决方案的链接。我希望它能帮助你。

public class Calculator { 

    private String distance(int destination, boolean isMiles) 
      throws IllegalArgumentException { 
      if (destination < 0) { 
       throw new IllegalArgumentException(); 
      } 
      return String.format(destination + " " + 
       new DecimalFormat("#.###").format(
         isMiles ? destination/0.621371192 : destination/1.609344)); 
     } 
} 

而在main方法的使用:

public static void main(String[] args) { 
    try { 
     System.out.println(new Calculator().distance(10, false)); // 10 km 
     System.out.println(new Calculator().distance(10, true)); // 10 m 
    } catch (IllegalArgumentException e) { 
     System.out.println("You pass wrong arguments to the method!"); 
    } 
} 

输出#1:

10 6.214 
10 16.093 

接着在for环可以在一列中打印的多个值。

for (int i = 0; i++ < 5;) { 
    System.out.println(new Calculator().distance(i, false)); 
} 

输出#2:

1 0.621 
2 1.243 
3 1.864 
4 2.485 
5 3.107 
+0

谢谢安德鲁,让我玩一下这个代码。我对Java仍然很陌生。不要超出你的方式,但如果你可以评论你的工作一点,所以我可以更容易地理解它,我真的很感激它! –

+0

@CoreyBryant,好吧,你在这里不明白什么? – Andrew

+0

@AndrewTobiko我不知道IllegalArumentException是什么,但我查了起来,我也从来没有见过尝试或抓住。 –

相关问题