gpt4 book ai didi

java - 有没有办法在程序完成后循环它?我总是遇到无限循环

转载 作者:行者123 更新时间:2023-12-01 11:47:31 25 4
gpt4 key购买 nike

我制作了一个工资程序,我需要循环它,以便它为多个员工运行。

现在,它对一个人来说工作得很好,但如果我在程序顶部添加一个 while(true){ ,它会无限循环并永远打印消息。我对 Java 还很陌生,所以任何建议都会受到赞赏!

import java.util.*;
import java.text.*;

public class Wages {
public static void main(String[] arg) {
DecimalFormat money = new DecimalFormat("$0.00");
int inTime = 0;
int outTime = 0;
int inMin = 0;//convert time to minutes for easier calculation
int outMin = 0;
int iLength = 0;
double minWorked = 0;
double hoursWorked = 0;
double totalPay = 0;
double PPH = 0; //pay per hour
Scanner sc = new Scanner(System.in);
String name = "";
String timeIn = "";

while (true) {
while (iLength < 3) { //loop if input is invalid
System.out.print("Please enter your name: ");
name = sc.nextLine();
name = name.trim(); //trim spaces
iLength = name.length();//check length
if (iLength < 3) {//error message
System.out.println("Please enter a name longer than 3 characters.");
}
}
try {
while ((inTime < 800 || outTime > 1900) || outTime <= inTime) {
System.out.print("Please enter your check in time: ");
inTime = sc.nextInt();
System.out.print("Please enter your check out time: ");
outTime = sc.nextInt();
if (inTime < 800 || outTime > 1900) {
System.out.println("Please enter work time between 800 and 1900.");
}
if (outTime <= inTime) {
System.out.println("Please enter a check out time later than your check in time.");
}
}
while (PPH < 7.75 || PPH > 15.20) {
System.out.print("Please enter your pay per hour: $");
PPH = sc.nextDouble();
if (PPH < 7.75 || PPH > 15.20) {
System.out.println("Please enter a pay between 7.75 and 15.20.");
}
}
inMin = (inTime / 100) * 60 + (inTime % 100);
outMin = (outTime / 100) * 60 + (outTime % 100);
minWorked = outMin - inMin;
hoursWorked = minWorked / 60;
totalPay = hoursWorked * PPH;
System.out.println("\nEmployee Name: " + name);
System.out.println("Check in time: " + inTime);
System.out.println("Check out time: " + outTime);
System.out.println("Hours worked: " + hoursWorked);
System.out.println("Pay per hour: " + money.format(PPH));
System.out.println("Total pay: " + money.format(totalPay));
}//try
catch (InputMismatchException ime) {
System.out.println("Please enter time and pay as numbers.");
}
}//while(true)
}//main
}//class

最佳答案

您永远不会重置输入变量。因此,当循环回到开始时,变量已经设置并且程序会跳过验证检查。

例如,在循环开始时我们设置 iLengthname 。说name="Alex"因此iLength=4 。这通过了while(iLength<3)查看。然后输入其余数据(让我们假装)并完成循环。然后我们回到代码while(iLength<3) 。因为我们还没有重置iLength , iLength仍然是 4,因此它甚至从不询问名称。

您需要在 while(true) 中声明变量循环,这意味着它们会在每个循环中被销毁并重新创建,或者您需要在每个循环结束时重置它们。例如: iLength=0;
name="";

还值得注意的是,您应该有办法打破无限循环。例如:

if (name.equalsIgnoreCase("exit")) return;

如果输入名称“exit”(无论大小写变化),这将结束程序。

关于java - 有没有办法在程序完成后循环它?我总是遇到无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29043940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com