Java do / while循环抵消前两个问题

时间:2013-09-19 19:30:17

标签: java loops boolean

我正在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);


  }

}

2 个答案:

答案 0 :(得分:5)

当您执行sc.nextDouble();时,nextDouble只会读取double并跳过表示新行的\n(按用户输入的键),所以它会请在下一个nextLine()下阅读!

您应该通过添加另一个sc.nextLine()来“吞下”这一新行。

答案 1 :(得分:1)

问题在于sc.nextDouble()方法。它将输入的下一个标记读作双精度并跳过剩余。所以当您使用nextLine()或{{1时使用next()方法时}}或nextInt()等方法。