I'm really new to coding and just got assigned my first coding homework involving methods and returns. I managed to struggle through and end up with this, which I'm pretty proud of, but I'm not quite sure it's right. Along with that, my return statements are all on the same lines instead of formatted how my teacher says they should be ("n is a perfect number", then the line below says "factors: x y z", repeated for each perfect number. Below are the exact instructions plus what it outputs. Anything will help!
Write a method (also known as functions in C++) named isPerfect that takes in one parameter named number, and return a String containing the factors for the number that totals up to the number if the number is a perfect number. If the number is not a perfect number, have the method return a null string (do this with a simple: return null; statement). Utilize this isPerfect method in a program that prompts the user for a maximum integer, so the program can display all perfect numbers from 2 to the maximum integer
286 is perfect.Factors: 1 2 3 1 2 4 7 14
It should be
6 is perfect Factors: 1 2 3 28 is perfect Factors: 1 2 4 7 14
public class NewClass { public static void main(String[] args) { Scanner input = new Scanner(System.in) ; System.out.print("Enter max number: ") ; int max = input.nextInt() ; String result = isPerfect(max) ; System.out.print(result) ; } public static String isPerfect(int number) { String factors = "Factors: " ; String perfect = " is perfect." ; for (int test = 1; number >= test; test++) { int sum = 0 ; for (int counter = 1; counter <= test/2; counter++) { if (test % counter == 0) { sum += counter ; } } if (sum == test) { perfect = test + perfect ; for (int counter = 1; counter <= test/2; counter++) { if (test % counter == 0) { factors += counter + " " ; } } } } return perfect + factors ; } }
https://stackoverflow.com/questions/65784101/formatting-returned-strings January 19, 2021 at 08:53AM
没有评论:
发表评论