Java 跳过系统输出,扫描下一行和if循环
这里是新的(对Java来说也是如此!)。我在这个网站上到处寻找我的问题的答案,但一无所获。此程序最多执行Java 跳过系统输出,扫描下一行和if循环,java,java.util.scanner,Java,Java.util.scanner,这里是新的(对Java来说也是如此!)。我在这个网站上到处寻找我的问题的答案,但一无所获。此程序最多执行scan.nextDouble语句 如果我输入工资值,如“8”,我会得到: 很明显,我下面的scan.nextLine和所有if-else语句都被忽略了。我错过了什么 import java.util.Scanner; import java.text.NumberFormat; public class Salary { public static void m
scan.nextDouble
语句
如果我输入工资值,如“8”,我会得到:
很明显,我下面的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()只读取下一个可用的双精度值,本身并不指向下一行
在实际扫描仪之前使用虚拟扫描仪.nextLine()。这样,您的光标就可以指向scanner.nextline()接收输入的下一行
-干杯:)当您使用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();
我建议在if语句中添加大括号(
{}
),现在只在它与给定的任何单词都不匹配的情况下(无论是“优秀”、“良好”还是“差”)新的工资将被计算出来。这就成功了。Thx!一旦我的程序开始工作,我就能够拍摄剩下的部分。@slaverock68很好。别忘了接受答案,这样人们就知道这个问题已经解决了。请投票给我的答案,并感谢你的输入。同上^Semper-Fi
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
scan.nextLine();
rating = scan.nextLine();