0

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

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;
    }
}
4

3 回答 3

1

更改repeat = sc.nextLine();repeat = sc.next();如果您不需要额外的行。只有当你是下一行时它才会得到它,你不是,所以它终止程序。

于 2013-09-25T23:25:35.197 回答
0

你之前在循环中Scanner调用之前的使用是. 调用不会消耗流中的换行符以输入每加仑成本。repeat = sc.nextLine();whilenextDoublenextDouble

在要求重复之前使用换行符:

System.out.print("Do it again? ");
String dummy = sc.nextLine();  // Add this line.
repeat = sc.nextLine();
于 2013-09-25T23:19:56.560 回答
0

使用重复 = sc.next(); 而不是重复 = sc.nextLine();

于 2013-09-25T23:32:22.620 回答