我在java中工作,只要有用户指定的项目,我希望我的循环运行。截至目前,代码运行一次迭代,并读取一个循环的结果,但它不会再继续。
如果用户说有3个项目,我希望代码在循环中运行3次并告诉我每个项目的总数。现在,它告诉我1个项目的总数,我是否指定项目数是1或5.
double projectBoardFootage = 1.0;
double projectBoardFootageTotal = 0.0;
int i = 0;
System.out.println("How many projects do you want to estimate?");
int numberOfProjects = scan.nextInt();
for(i = 0; i < numberOfProjects; ++i) {
while (projectBoardFootage > 0) {
System.out.println("Enter your board footage for Project #" + (i + 1) + " (0 to exit)");
projectBoardFootage = scan.nextDouble();
projectBoardFootageTotal += projectBoardFootage;
}
System.out.println("The raw board footage for Project #" + (i + 1) + " is: " + projectBoardFootageTotal);
}
答案 0 :(得分:0)
您的代码中的问题是您使用变量projectBoardFootage来终止循环。 想想当这个值设置为0时会发生什么。 我们退出while循环,值永远不会再次更改。所以从那时起,每次迭代都会立即结束。
更好的解决方案是做这样的事情:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many projects do you want to estimate?");
int numberOfProjects = scan.nextInt();
for(int i = 0; i < numberOfProjects; ++i) {
foobar(scan, i+1);
}
}
private static void foobar(Scanner scan, int projectNr)
{
boolean wantsToQuit = false;
double projectBoardFootageTotal = 0;
while (!wantsToQuit) {
System.out.println("Enter your board footage for Project #" + projectNr + " (q to exit)");
String tmp = scan.next();
if(tmp.equalsIgnoreCase("q"))
wantsToQuit = true;
else
projectBoardFootageTotal += Double.parseDouble(tmp);
}
System.out.println("The raw board footage for Project #" + projectNr + " is: " + projectBoardFootageTotal);
}
此代码还可确保用户输入比#0; 0&#39;更合理的密钥代码。退出。
答案 1 :(得分:0)
也许您想重新初始化总的电路板素材以清除之前的迭代计数?
for(i = 0; i < numberOfProjects; ++i) {
projectBoardFootageTotal = 0.0;
while (projectBoardFootage > 0) {
System.out.println("Enter your board footage for Project #" + (i + 1) + " (0 to exit)");
projectBoardFootage = scan.nextDouble();
projectBoardFootageTotal += projectBoardFootage;
}
System.out.println("The raw board footage for Project #" + (i + 1) + " is: " + projectBoardFootageTotal);
}