所以这个程序做的是使用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;
}
}
你确实返回了一些东西,你只是不打印它。试一试:
System.out.println(lcm(firstNumber, secondNumber));
您没有打印返回的值
System.out.println(lcm(firstNumber, secondNumber));
正如你所写的,
lcm(firstnumber, secondnumber);
此方法将返回int类型值,但在您的代码中,您没有在任何变量中获取返回的值。
所以,你应该这样写:
int variable=lcm(firstnumber, secondnumber);