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;
}
添加回答
舉報