当我运行它时,它会提示数英里,然后会挂起并且没有进展要求英里/小时。它应该回到循环中,如果输入0为里程,它将结束程序。为什么在我玩完之后会挂断电话?
import java.text.NumberFormat;
import java.util.Scanner;
// use integer division to divide time into hours and minutes?
public class TravelTimeApp
{
private static double miles;
private static double milesPerHour;
private static double hours;
private static int minutes;
private static int hoursInt;
public TravelTimeApp ()
{
miles = 0;
}
public static void main(String[] args)
{
//NumberFormat
NumberFormat onePlace = NumberFormat.getNumberInstance();
onePlace.setMaximumFractionDigits(1);
// create the Scanner object
Scanner sc = new Scanner(System.in);
System.out.printf(" Enter miles traveled, or a zero (0) to exit -> ");
miles = sc.nextDouble();
if (miles == 0)
{
System.out.printf("\n Program completed.");
System.exit(0);
}
while(miles != 0)
{
System.out.printf(" Enter miles per hour rate of travel -> ");
milesPerHour = sc.nextDouble();
// calculate the travel time in hours with decimal division
hours = miles / milesPerHour;
// get number of minutes as an int
minutes = (int) (hours * 60);
// use integer arithmetic to get hours and minutes as int values
hoursInt = minutes / 60;
minutes = minutes % 60;
// display the result
System.out.printf(" \nEstimated Travel Time (%,.1f miles at %,.1f mph)\n", miles,milesPerHour);
System.out.printf(" Hours%,10d\n", hoursInt);
System.out.printf(" Minutes%,8d\n\n", minutes);
}
}
}
答案 0 :(得分:5)
你的程序没有挂断。它无休止地计算循环中的代码,因为你从未在循环中设置miles
变量。
说得直截了当,因为你需要while(miles != 0)
miles = sc.nextDouble();
,但我真的认为你的意思是while(milesPerHour != 0)
和milesPerHour = sc.nextDouble();
。
请注意每个变量的用途,因为您正在做的是覆盖用于计算输出的miles
变量。您混淆了miles
和milesPerHour
。
还要在循环之前删除if语句,它只运行一次并且是多余的。虽然你对System.exit()
有正确的想法,但循环之后没有代码,所以当循环从miles
为0时,你的程序应该退出。
答案 1 :(得分:0)
由于您没有修改miles
循环内的while
,因此循环永远不会终止。
您必须再次使用miles
作为用户的输入。