跳过 system out,扫描 nextLine,如果循环

Skips over system out, scan nextLine, and if loops

这里是新的(并且 Java!)。我在网站上搜索了我的问题的答案,但一无所获。该程序执行到 scan.nextDouble 语句。

如果我输入薪水值,例如“8”,我得到:

/////OUTPUT/////  
Enter the performance rating (Excellent, Good, or Poor):  
Current Salary:       .00  
Amount of your raise: [=10=].00  
Your new salary:      .00  
/////END OF OUTPUT/////

很明显,我后面的 scan.nextLine 和所有 if-else 语句都被绕过了。我错过了什么?

    import java.util.Scanner;
    import java.text.NumberFormat;

public class Salary 
{

    public static void main(String[] args) 
    {
        double currentSalary;  // employee's current  salary
        double raise = 0;          // amount of the raise
        double newSalary = 0;      // new salary for the employee
        String rating;         // performance rating
        String rating1 = new String("Excellent");
        String rating2 = new String("Good");
        String rating3 = new String("Poor");

        Scanner scan = new Scanner(System.in);

        System.out.print ("Enter the current salary: ");
        currentSalary = scan.nextDouble();
        System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
        rating = scan.nextLine();

        // Compute the raise using if ...
        if (rating.equals(rating1))

            raise = .06;

        else

        if (rating.equals(rating2))

            raise = .04;

        else

        if (rating.equals(rating3))

            raise = .015;

        else

            newSalary = currentSalary + currentSalary * raise;

         // Print the results
        {
        NumberFormat money = NumberFormat.getCurrencyInstance();
        System.out.println();
        System.out.println("Current Salary:       " + money.format(currentSalary));
        System.out.println("Amount of your raise: " + money.format(raise));
        System.out.println("Your new salary:      " + money.format(newSalary));
        System.out.println();
        }
    }
}

Scanner.nextDouble() 只是读取下一个可用的双精度值,它本身并不指向下一行。

在您实际的 scanner.nextLine() 之前使用一个虚拟的 scanner.nextLine() 。让您的光标指向下一行,您的 scanner.nextline() 从中获取输入。

-干杯:)

当您使用 scanner.nextDouble() 扫描输入时,它仅采用浮点值并将换行符留在缓冲区中,因此之后当您执行 scanner.nextLine(() 它采用新的line character and returns empty string.Put another scanner.nextLine() before scanning the next line to eat up the new line character

currentSalary = scan.nextDouble();
    System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
    scan.nextLine(); 
    rating = scan.nextLine();