这里新(和Java!)。我在网站上搜索了我的问题的答案,但没有结果。该程序最多执行scan.nextDouble
语句。
如果我输入薪水值,例如“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 :(得分:0)
Scanner.nextDouble()只读取下一个可用的double值,而不是指向下一行。
在实际的之前使用虚拟scanner .nextLine()。使光标指向scan.nextline()从中获取输入的下一行。
-cheers:)
答案 1 :(得分:0)
当你使用scanner.nextDouble()扫描输入时,它只接受浮点值并在缓冲区中留下新行字符,所以当你执行scanner.nextLine(()它接受新行字符并返回空字符串。在扫描下一行之前输入另一个scanner .nextLine()以占用新行字符
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
scan.nextLine();
rating = scan.nextLine();