Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java While语句循环错误_Java_Loops_While Loop_Repeat_Mpeg - Fatal编程技术网

Java While语句循环错误

Java While语句循环错误,java,loops,while-loop,repeat,mpeg,Java,Loops,While Loop,Repeat,Mpeg,嘿,我对这段代码有一个问题,因为当我输入字符串repeat的值时,它没有循环。我无法理解我做错了什么 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

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

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()之前使用的
扫描仪
中,而
循环是
nextDouble
。调用
nextDouble
不会消耗流中输入每加仑成本的换行符

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

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

更改
repeat=sc.nextLine()
重复=sc.next()如果不需要额外的行。它只在你是下一行的一个用户时得到它,而你不是,因此它终止程序。

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

我可能已经完全离开了
nextLine
,而是使用了
next
。哦,
stringdummy=
有什么意义呢?您不需要使用返回值。@Dukeling只是为了强调它是一个一次性值。我尝试了一个一次性值,当我测试并编译它时,它导致了一个异常错误并崩溃。用sc.next替换sc.nextLine似乎就足够了。在while语句上加一个断点,看看“repeat”的值是多少。