Question

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;
    }
}
Was it helpful?

Solution

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

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

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top