我是论坛新手,所以首先我想说“嗨”!我是 Java 编程新手,正在尝试使用三个 while 循环制作一个简单的工资计算程序。
第一个 while 循环使程序继续运行,直到用户输入标记“停止”。第二个和第三个循环是错误陷阱,确保用户在继续之前输入正数。
由于某种原因,while 循环不起作用,我已经尝试了我能想到的所有变体。程序运行得很好,只是忽略了 while 循环。如果有人可以就我做错的事情提供一些建议,我将非常感激。
如果有帮助的话,我正在使用 NetBeans 8.0 IDE。
这是我的代码:
Import java.util.*;
Import java.text.*;
public class PayrollProgramVersion2
{
//begin main program
public static void main(String[] args)
{
//declare new scanner
Scanner sc = new Scanner (System.in); // declare new scanner object
DecimalFormat Dollars = new DecimalFormat ("$0.00"); //format for dollars
String Employee; //employee's name
Double Hours, //hours worked
Rate, //pay rate
Pay; // Hours * Rate
Boolean Continue = true; // sentinel for program loop
//welcome user, prompt for employee name, and assign input to Employee
System.out.println ("Welcome to the payroll program!");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
// while loop continues program until user enters "stop"
while (Continue == true)
{
if (Employee.equalsIgnoreCase("stop"))
{
Continue = false;
} // end if
else
{
//prompt for hours worked and assign to Hours
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
}
//prompt for pay rate and assign to Rate
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Rate < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
}
Pay = Hours * Rate; // calculate payrate
//display results
System.out.println(Employee+ "'s paycheck is " +(Dollars.format(Pay))+ ".");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
} //end else
} //end while
System.out.println ("Thank you for using the payroll program. Goodbye!");
} // end main
} // end program
最佳答案
据我所知,您应该将 while (hours<0)
更改为 while (hours<0 || hours == null)
。
这是因为...据我所知,您初始化了时间。但没有向其中输入任何值。所以它仍然是 null
。您也可以尝试将 while 更改为 if。
希望这有帮助。它可能默认为 0,但出于测试目的,有控制台输出可能是值得的。
System.out.println(hours);
在 while 循环之前查看您的程序将 hours
读取为什么。
希望这有帮助。
关于java - 运行时忽略 While 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24731302/