문제

So what this program does is take two numbers as input using the Scanner class, and calculates the lowest common multiple of those two numbers. Everything seems to be working, except the lcm method won't return anything. I may have messed something up with my 'break' statements, but I didn't know any other way to get out of the if statement that is nested in a while loop. One more question: Is using a while(True) loop good practice or bad practice? Because I've seen lots of mixed opinions on it. If anyone has any better alternatives to while(True) loops I'd be happy to hear them. Thank you!

// 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;
    }
}
도움이 되었습니까?

해결책

You do return something, you're just not printing it. Just try:

System.out.println(lcm(firstNumber, secondNumber));

다른 팁

You are not printing the returned value

System.out.println(lcm(firstNumber, secondNumber));

As you had written,

lcm(firstnumber, secondnumber);

this method will return an int type value, but in your code, you are not obtaining the returned value in any variable.

So, you should write like this :

int variable=lcm(firstnumber, secondnumber);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top