【发布时间】:2014-01-15 00:07:18
【问题描述】:
所以这个程序所做的是使用 Scanner 类将两个数字作为输入,并计算这两个数字的最小公倍数。一切似乎都在工作,除了 lcm 方法不会返回任何东西。我的“break”语句可能搞砸了,但我不知道有任何其他方法可以摆脱嵌套在 while 循环中的 if 语句。还有一个问题:使用 while(True) 循环是好做法还是坏做法?因为我看到了很多关于它的不同意见。如果有人对 while(True) 循环有更好的选择,我会很高兴听到它们。谢谢!
// LCM Calculator
// Author: Ethan Houston
// Language: Java
// Date: 2013-12-27
import java.io.*;
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("This is a LCM calculator\n");
System.out.println("Enter your first number: ");
int firstNumber = scanner.nextInt();
System.out.println("Enter your second number: ");
int secondNumber = scanner.nextInt();
lcm(firstNumber, secondNumber);
}
public static int lcm(int one, int two) {
int counter = Math.min(one, two);
int initialCounter = counter;
boolean running = true;
while (running) {
if (counter % one == 0 && counter % two == 0) {
break;
} else {
counter += initialCounter;
}
}
return counter;
}
}
【问题讨论】:
-
while (true)将永远运行。您必须在某个时间点更改running的值。 -
@ShashankKadne 里面有休息。 :)
-
您没有对
lcm方法返回的值做任何事情。尝试打印:System.out.println(lcm(firstNumber, secondNumber)); -
@Leri : 谢谢,我想我需要点咖啡..:)
-
If anyone has any better alternatives to while(True) loops I'd be happy to hear them有但不能替代:while (!yourConditionForBreak) { counter += initialCounter; }while循环的正确构造是while (conditionWhenLoopShouldExecute) {}
标签: java if-statement while-loop break lcm