Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
64 views
in Technique[技术] by (71.8m points)

java - Struggling with harshad algorithm ? why no output?

A harshad number is one that can be divided evenly by the sum of its digits. For example, 24 is a Harshad number because 24 / (2 + 4) = 4. For example, 23 is not a Harshad number because 23 / (2 + 3) = some decimal. Here is my attempt to prompt the user for an integer, check if said integer is a Harshad number, and if it is output it; if not, keep increasing the number by 1 until we find one to output.

import java.io.*;

public class harshad {

    public static void main(String[] args) throws NumberFormatException, IOException {
        // TODO Auto-generated method stub
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String number = reader.readLine(); // "23"
        boolean isHarshad = false;
        while (isHarshad = false) {
            int sum = 0;
            String[] parts = number.split(""); // ["2", "3"]
            int num = Integer.parseInt(number); // 23
            for (int i = 0; i < parts.length; i++) {
                sum += Integer.parseInt(parts[i]); // 5
            }
            if (num % sum == 0) { // clean division
                System.out.println(num); // should work for number 24
                isHarshad = true; // break loop
            } else {
                number = Integer.toString(num++); // "24"
            }
        }
    }
}
question from:https://stackoverflow.com/questions/65875393/struggling-with-harshad-algorithm-why-no-output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace while (isHarshad = false) with while (isHarshad == false) or even better while (!isHarshad), otherwise you are making an assignment instead of a comparison.

Replace number = Integer.toString(num++); with number = Integer.toString(++num); otherwise the increment happens after the assignment, instead of before.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...