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 に答える