2013-09-25 216 views
0

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

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

在你的while语句中加上一个断点,看看他'重复'的价值是什么。 – DSway

回答

1

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

0

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

消耗换行符要求重复之前:

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

我可能刚刚从'nextLine'完全移开,而使用'next'。哦,'String dummy ='有什么意义呢?你不需要**来使用返回值。 – Dukeling

+0

@Dukeling只是为了强调这是一次性价值。 – rgettman

+0

我曾尝试过一次性的价值,当我测试运行它并编译它时,它会导致异常错误并崩溃。用sc.next替换sc.nextLine似乎就足够了。 – Andrew

0

use repeat = sc.next(); 而不是 repeat = sc.nextLine();