gpt4 book ai didi

java - while语句循环错误

转载 作者:行者123 更新时间:2023-12-01 14:04:37 26 4
gpt4 key购买 nike

嘿,我对这段代码一直有疑问,因为当我输入字符串重复值时它没有循环。我无法理解我做错了什么。

import java.util.Scanner;
public class MpgCalculator
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the MPG and CPM Calculator!");
double startOd, endOd, gallons, cost, mpg, cpm;
String repeat = "yes";
while(repeat.equals("yes")||repeat.equals("Yes")||repeat.equals("y")||repeat.equals("Y"))
{
System.out.println("Please Enter:");
System.out.print("\tYour Starting Odometer Reading: ");
startOd = sc.nextDouble();
System.out.print("\tYour Ending Odometer Reading: ");
endOd = sc.nextDouble();
System.out.print("\tThe Amount of Gallons Used: ");
gallons = sc.nextDouble();
System.out.print("\tThe Cost-per-Gallon That You Spent: ");
cost = sc.nextDouble();
mpg = getMpg(startOd, endOd, gallons);
cpm = getCpm(mpg, cost);
System.out.println("\nYour Miles-per-Gallon is " + mpg + ".");
System.out.println("Your Cost-per-Mile is " + cpm + ".");
System.out.print("Do it again? ");
repeat = sc.nextLine();
}
}
public static double getMpg(double startOd, double endOd, double gallons)
{
double mpg;
mpg = (endOd - startOd) / gallons;
return mpg;
}
public static double getCpm(double mpg, double cost)
{
double cpm;
cpm = cost / mpg;
return cpm;
}
}

最佳答案

如果不需要额外的行,请将 repeat = sc.nextLine(); 更改为 repeat = sc.next();。只有当您是下一行时它才会获取它,而您不是,因此它会终止程序。

关于java - while语句循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19016760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com