+ 1

What’s the wrong in the code?

import java.util.Scanner; public class program { public static int factorial (int n){ for (int i=1 ; i<=n ; i++){ n=n*i; } return n; } public static boolean isStrongNumber (int x){ int sum=0; x=1; while(x>0){ int n=x%10; sum +=factorial(n); x/=10; } if (x==sum){ return true; } else{ return false; } } public static void main(String[] args) { Scanner input = new Scanner (System.in); System.out.print("Enter a positive integer: "); int p = input.nextInt(); for(int x=1 ; x<=p ; x++){ boolean a = isStrongNumber(x); if (a == true){ System.out.print(x+" "); } } } }

2nd Jun 2020, 5:42 AM
Zaynab
7 Réponses
+ 2
The line if(boolean a = true) Maybe should be like this if(a == true) Not sure about other parts of the code ...
2nd Jun 2020, 6:21 AM
Ipang
+ 1
Hi Zaynab, Please only mention someone in the thread Description. Mentions do not work if you put them in the thread tags.
2nd Jun 2020, 6:06 AM
Ipang
+ 1
A number is called a Strong number if the sum of the factorial of its digits is equal to the number itself. For example: 145 is a Strong number since: 1! + 4! + 5! = 1 + 24 + 120 = 145 a) Write a method with the following header that takes an integer n and returns the value of n! (pronounced n factorial) computed as follows: public static int factorial(int n) Note that 0! = 1 and n! = n * (n-1) * (n-2)*.....*1. Example: factorial(4) will return 24 which is = 4*3*2*1. b) Write a method with the following header that takes an integer x and returns true if x is a Strong number, otherwise it returns false. public static boolean isStrongNumber(int x) Note that the isStrongNumber method should call the factorial method to compute the factorial of each digit in x. c) Write a main method that prompts the user to input an integer p, then calls the method isStrongNumber to output all the strong numbers <=p. this is the question
2nd Jun 2020, 9:08 AM
Zaynab
0
okay thank you Have an idea about the error in the code?
2nd Jun 2020, 6:12 AM
Zaynab
0
You wrote the bracket two times after "class program". import java.util.Scanner; public class program { { // don't write this bracket public static int factorial (int n){............ It should be like this: import java.util.Scanner; public class program { public static int factorial (int n){............ Hope this helps
2nd Jun 2020, 8:57 AM
H-J
H-J - avatar
0
I corrected this but this is not the error anway thank you
2nd Jun 2020, 9:01 AM
Zaynab
0
What type of error do you recieve or do you mean bugs by error.If there is a bug , then could you tell me what the code is for.
2nd Jun 2020, 9:06 AM
H-J
H-J - avatar