In: Computer Science
Having a problem with syntax error in Java:
JAVA (Perfect Numbers) An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a method isPerfect that determines whether parameter number is a perfect number. Use this method in an application that displays all the perfect numbers between 1 and and integer entered by the user. Display the factors of each perfect number to confirm that the number is indeed perfect. Challenge the computing power of your computer by testing numbers much larger than 1000. Display the results.
import java.util.Scanner;
public class IsPerfect {
static boolean isPerfect(int n)
{ int Sum = 0;
for (int i=1; i<n ; i++) {
if(n% i == 0) {
Sum = Sum +
i;
}
}
if (Sum == n) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
int user_input; // taking user input
try (Scanner input = new Scanner(System.in)){
System.out.println("Perfect numbers between 1 and "+
user_input + "are:");
for (int i=1; i<= user_input; i++){
if (isPerfect(i)){
System.out.println(i);
}
}
}
}
Answer:
Here is the corrected java code as per your requirement
Raw code:
import java.util.Scanner;
//class named IsPerfect
public class IsPerfect {
//static method to verify weather Perfect number of not
static boolean isPerfect(int n)
//declaring sum value
{
int Sum = 0;
//for loop over the value time
for (int i=1; i<n ; i++) {
//checking if the value leaves reminds 0 multiplied with i
if(n% i == 0) {
//if yes increment sum
Sum = Sum + i;
}
}
//if sum is same value
if (Sum == n) {
//return true it as IsPerfect number
return true;
}
//else no
else {
return false;
}
}
//main method
public static void main(String[] args) {
//declaring varialble
int user_input;
// taking user input
Scanner input = new Scanner(System.in);
//getting integer
user_input=input.nextInt();
//print on the console
System.out.println("Perfect numbers between 1 and "+ user_input + "are:");
//iterate over the values from 1 to user_input range
for (int i=1; i<= user_input; i++){
//check every value if its Perfect number
if (isPerfect(i)){
//if it is print the valu
System.out.println(i);
}
}
}
}
Editor:
output:
Hope this helps you! If you still have any doubts or queries please feel free to comment in the comment section.
"Please refer to the screenshot of the code to understand the indentation of the code".
Thank you! Do upvote.