简体   繁体   English

While语句循环错误

[英]While statement loop error

Hey I have been having an issue with this code because it has not been looping when I input a value for the String repeat. 嘿,我一直对此代码有疑问,因为当我为String repeat输入一个值时,它还没有循环。 I am unable to understand whatever it is that I'm doing wrong. 我无法理解我做错了什么。

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

Change repeat = sc.nextLine(); 更改repeat = sc.nextLine(); to repeat = sc.next(); repeat = sc.next(); If you don't need the extra line. 如果您不需要多余的线。 It only gets it if you are an the next line, which you are not, so it terminates the program. 仅当您不是下一行时,它才会获取它,否则,它将终止程序。

The previous use of your Scanner prior to calling repeat = sc.nextLine(); 调用repeat = sc.nextLine();之前对Scanner的先前使用repeat = sc.nextLine(); in your while loop is nextDouble . 在您的while循环中是nextDouble Calling nextDouble does not consume the newline character in the stream from entering the cost per gallon. 从输入每加仑成本开始,调用nextDouble不会消耗流中的换行符。

Consume the newline character before asking to repeat: 在要求重复之前,请使用换行符:

System.out.print("Do it again? ");
String dummy = sc.nextLine();  // Add this line.
repeat = sc.nextLine();

use repeat = sc.next(); 使用repeat = sc.next(); instead of repeat = sc.nextLine(); 而不是repeat = sc.nextLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM