2015-06-20 19 views
0

此处新增(对Java!)。我在网站上搜索了解我的问题的答案,但没有成功。该程序执行到scan.nextDouble语句。跳过系统,扫描nextLine,如果出现循环

如果我进入一个工资值,如 “8,” 我得到:

/////OUTPUT///// 
Enter the performance rating (Excellent, Good, or Poor): 
Current Salary:  $8.00 
Amount of your raise: $0.00 
Your new salary:  $8.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(); 
     } 
    } 
} 
+0

我建议加括号('{}')到如果 - 现在只有在与任何给定的词('优秀','好'或'差')相匹配的情况下,新的工资才会被计算出来 – Caramiriel

回答

0

当您使用扫描scanner.nextDouble(输入)只需要浮动值和叶新行字符的缓冲区,以便以后,当你做scanner.nextLine(()它需要换行字符,并返回空string.Put另一个scanner.nextLine()扫描下一行之前吃了换行字符

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

这个技巧。谢谢!一旦我开始工作,我就可以拍摄剩余的程序。 – slaverock68

+0

@ slaverock68不错,它的工作。不要忘记接受答案,让人们知道这个问题也解决了,请做upvote我的答案 –

0

Scanner.nextDouble()只是读取下一个可用的double值,而不会自己指向下一行。

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

-cheers :)

+0

并且谢谢你ü以及您的意见。同上^。 Semper Fi – slaverock68