所以这个程序所做的是使用 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;
}
}