0

我在我的java编程课上写了一个程序。该程序是一个简单的 do/while 循环,它使用扫描程序类和一个布尔值的启动读取来询问一些问题。当循环第一次迭代时,它可以正常工作,但是当它第二次迭代时,它会同时显示第一个问题和第二个问题,并且只允许我回答第二个问题。我希望这很清楚。任何人有任何见解?代码:

      /*
      * Programmed By: Cristopher Ontiveros
      * Date: 9/19/13
 * Description: Compute weekly salary and witholding for employees
 */
package project.one.cristopher.ontiveros;

import java.util.Scanner;
public class ProjectOneCristopherOntiveros {

     static Scanner sc = new Scanner(System.in);
     public static void main(String[] args) {
     String fName, lName;
     double rate=0, wPay=0, withholding=0;
     int option = 0;
     boolean badval = true;
         System.out.println("Welcome to the Pay Calculator");


     do{
        System.out.println("Enter employee first name: ");
        fName = sc.nextLine();
        System.out.println("Enter employee last name: ");
        lName = sc.nextLine();
        System.out.println("Enter employee hourly rate: ");
        rate = sc.nextDouble();
        wPay = (rate * 40);
        withholding = (wPay * .20);
        System.out.println("Employee " + fName + " " + lName + "\nHourly Rate: " + rate + "\nWeekly Pay: " + wPay + "\nWithholding Amount: " + withholding);


         System.out.println("Would you like to enter another employee? (1 = yes, 2 = no)");
     option = sc.nextInt();
     sc.nextLine()
     if(option == 1){
         badval = true;

     } else {
         badval = false;

     }
     }while(badval);


  }

}

4

2 回答 2

5

当您这样做时sc.nextDouble();nextDouble仅读取double并跳过\n指示新行的 (用户按 Enter 键),因此下一个将读取它nextLine()

您应该通过添加另一个sc.nextLine().

于 2013-09-19T19:31:53.643 回答
1

问题出在sc.nextDouble()方法上。它将输入的下一个标记读取为双精度并跳过剩余的。因此,nextLine()当您使用next()nextInt()nextDouble()等方法时,您会使用方法。

于 2013-09-19T19:35:00.117 回答