4 回答
TA贡献1785条经验 获得超4个赞
您需要检查用户是否在while循环内输入了-1。如果这样做,请使用 退出循环break,然后终止程序。
mpg仍在循环内打印,但仅在进行检查后打印。这确保用户给出了有效的输入。
我决定设置循环条件,因为如果ortrue为 -1 ,则循环应该中断。miles gallons
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int miles = 1;
int gallons = 1;
int totalMiles = 0;
int totalGallons = 0;
float mpg = 0;
while (true) {
System.out.println("Enter miles or -1 to exit");
miles = input.nextInt();
if (miles == -1) break;
System.out.println("Enter gallons or -1 to exit");
gallons = input.nextInt();
if (gallons == -1) break;
totalMiles = totalMiles + miles;
totalGallons = totalGallons + gallons;
mpg = (float) totalMiles / totalGallons;
System.out.println(mpg);
}
input.close();
System.out.print("Terminate");
}
TA贡献1817条经验 获得超14个赞
只需在 while 循环中添加 2 个附加条件(如果带有中断)即可立即退出 while
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// processing phase
int miles = 1;
int gallons = 1;
int totalMiles = 0;
int totalGallons = 0;
float mpg = 0;
System.out.println("Enter miles or -1 to exit");
miles = input.nextInt();
System.out.println("Enter gallons");
gallons = input.nextInt();
while (miles != -1) {
System.out.println("Enter miles or -1 to exit");
miles = input.nextInt();
if(miles == -1) break;
System.out.println("Enter gallons or -1 to exit");
gallons = input.nextInt();
if(gallons == -1) break;
totalMiles = totalMiles + miles;
totalGallons = totalGallons + gallons;
}
if (miles == -1) {
System.out.print("Terminate");
}
else{
mpg = (float) totalMiles / totalGallons;
System.out.println(mpg);
}
}
}
TA贡献1833条经验 获得超4个赞
这是完成的工作代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int miles = 0;
int gallons = 0;
int totalMiles = 0;
int totalGallon = 0;
double mpg = 0;
double totalMpg = 0;
while(miles != -1){
System.out.println("Enter mileage or -1 to exit: ");
miles = input.nextInt();
if(miles == -1){
break;
}
System.out.println("Enter gallons or -1 to exit: ");
gallons = input.nextInt();
mpg = (double) miles / gallons;
System.out.printf("MPG: %.4f%n", mpg);
if(gallons == -1){
break;
}
totalMiles = totalMiles + miles;
totalGallon = totalGallon + gallons;
}
if (miles == -1){
totalMpg = (double) totalMiles / totalGallon;
System.out.printf("Total used is %.4f%n", totalMpg);
}
}
TA贡献1829条经验 获得超6个赞
whileJava 仅在每次完成时评估循环。因此,您需要手动检查是否为miles-1并打破循环。
while (miles != -1) {
System.out.println("Enter miles or -1 to exit");
miles = input.nextInt();
if (miles == -1) break;
System.out.println("Enter gallons or -1 to exit");
gallons = input.nextInt();
totalMiles = totalMiles + miles;
totalGallons = totalGallons + gallons;
}
添加回答
举报