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 ;
}
}
Couple of things you could do:
Firstly, you do not need two loops to do this. You can run one loop till number and keep checking if it's divisible by the iterating variable. If it is, then add it to a variable called sum.
Example:
.
factors = []; //this can be a new array or string, choice is yours
sum=0;
for(int i=1; i<number; i++){
if(number % i == 0){
sum += i;
add the value i to factors variable.
}
}
after this loop completes, check if sum == number, the if block to return the output with factors, and else block to return the output without factors or factors = null(like in the problem statement)
In your return answer add a newline character between perfect and the factors to make it look like the teacher's output.
You can try the solution below:
public String isPerfect(int number) {
StringBuilder factors = new StringBuilder("Factors: ");
StringBuilder perfect = new StringBuilder(" is perfect.");
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
factors.append(" " + i);
}
}
if (sum == number) {
return number + "" + perfect.append(" \n" + factors);
}
return number + " is not perfect";
}
Keep separate variables for your template bits for the output and the actual output that you are constructing. So I suggest that you don’t alter factors and perfect and instead declare one more variable:
String result = "";
Now when you’ve found a perfect number, add to the result like this:
result += test + perfect + '\n' + factors;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
result += counter + " ";
}
}
result += '\n';
I have also inserted some line breaks, '\n'. Then of course return the result from your method:
return result;
With these changes your method returns:
6 is perfect.
Factors: 1 2 3
28 is perfect.
Factors: 1 2 4 7 14
Other tips
While your program gives the correct output, your method doesn’t follow the specs in the assignment. It was supposed to check only one number for perfectness. Only your main program should iterate over numbers to find all perfect numbers up to the max.
You’ve got your condition turned in an unusual way here, which makes it hard for me to read:
for (int test = 1; number >= test; test++) {
Prefer
for (int test = 1; test <= number; test++) {
For building strings piecewise learn to use a StringBuffer or StringBuilder.
Link
Java StringBuilder class on Javapoint Tutorials, with examples.
Related
This question already has answers here:
How to remove the last comma from the output in java? [duplicate]
(4 answers)
Closed 3 months ago.
public class Main {
public static void main(String[] args) {
// positive number
int number = 6;
System.out.print("Factors of " + number + " are: ");
// loop runs from 1 to 60
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + ",");
}
}
}
}
And my output is "1,2,3,6," but i want it like "1,2,3,6"
How can i do that?
No matter what i do it did not worked.
The simple and robust solution is to store the values in a list, and only then display them. This way you'll easily know when you're printing the last element. Besides, then you could just do something like:
List<String> divisors = new ArrayList<>();
// loop runs from 1 to 60
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
divisors.add(String.valueOf(i));
}
}
System.out.println(String.join(",", divisors));
Solution written by #abel1502 is the simplest if you want to display the values and keep them to use elsewhere. If you just want to display them, then there are more modern ways to do it (if you use a recent version of Java) :
var number = 60;
System.out.println(
IntStream.rangeClosed(1, number)
.filter(i -> number % i == 0)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","))
);
There are multiple ways to solve it. In your case since the last 'i' in the loop is always number itself, and it should be on the list since (number%number==0), you can simply do something like this:
public class Main {
public static void main(String[] args) {
// positive number
int number = 6;
System.out.print("Factors of " + number + " are: ");
// loop runs from 1 to 60
for (int i = 1; i < number; ++i) { //< instead of <=, to exclude i==number
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + ",");
}
}
//in your case
System.out.print(number);
}
}
Hi everyone, I'm making a java program that will display all perfect numbers in a given range. I have to do this by using method and this is my code:
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++){
String result = isPerfect(i);
System.out.println(result);
}
}
public static String isPerfect(int num){
String result = "";
int sum = 0;
for (int i = 1; i < num; i++){
if ((num % i) == 0){
sum += i;
}
}
if (sum == num){
result = "Number " + num + " is a perfect number";
}else{
result = "Number " + num + " is not a perfect number";
}
return result;
}
I expect to get a list consisting only of perfect numbers which for range from 1 to 1000 are 6, 28 and 496.
For the actual result I get these numbers but I also get the line from else part in the method, that is "Number #num is not a perfect number". I tried changing the return method but I couldn't find a solution to this. I put an empty string when the result is not true but then I get my line for perfect number 6 and then everything till the next perfect number is empty line, in this case from 6 and 28 there are 22 empty lines. How can I change this so my method doesn't return anything if the result is not the one that I want?
pic of my result
So I'd like not to get anything from that pic except for "Number 496 is a perfect number"
You are really close, there is one thing that I would change and that's returning a boolean rather than a String. This way the method isPerfect will return either true or false, which is kind of logical as it's either a perfect number or its not.
And then from that point you can print the perfect numbers:
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++){
if(isPerfect(i)){
System.out.println("Number "+ i + " is a perfect number");
}
}
}
public static boolean isPerfect(int num){
int sum = 0;
for (int i = 1; i < num; i++){
if ((num % i) == 0){
sum += i;
}
}
if (sum == num){
return true;
}
return false;
}
Just remove println, and in your if do this: "is a perfect number\n"
Then in your else, put empty string. So this if you want to stick to yuor code and dont want to change anything. If you want to modify your code a lot use #Fubars method which is also correct
Is there any better logic that can be applied to magic numbers?
Or is there a magic number that I am missing out on?
Please help me out with this simplest working code!
A Magic number is a number whose sum of digits eventually leads to 1.
Example#1: 19 ; 1+9 =10 ; 1+0 = 1. Hence a magic number.
Example#2: 226; 2+2+6=10; 1+0 =1. Hence a magic number.
Example#3: 874; 8+7+4=19; 1+9=10; 1+0=1. Hence a magic number.
boolean isMagic ( int n ) {
return n % 9 == 1;
}
Well, I'm not 100% that the code you placed would work to get a "magic number", but my approach to the problem would be different.
First, I'd receive a String, so that I can get the different digits of the number with a String.charat.
Then I'd use a while cycle to sum the numbers until it gets a single digit number, then check if it's 1.
The code would be
boolean isMagicNumber(String number) {
int[] digits = new int[number.length()];
int sum = 99;
while(sum/10 >= 1) {
sum = 0;
for(int i = 0; i < number.length(); i++) {
sum += Integer.parseInt(""+number.charAt(i));
}
if(sum == 1) {
return true;
}
}
return false;
}
There might be a better solution, but this is what I'd do to solve the problem.
The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}
I have to write a program using loops that calculates the sum of all odd numbers between a and b (inclusive), where a and b are inputs.
I made this (below) and it works fine, but I noticed one problem with it: when i enter a larger number followed by a smaller number for the inputs, it returns 0, but when i enter the smaller number first it works perfectly. Any quick fixes for this? :)
import java.util.Scanner;
public class ComputeSumAAndB
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter 2 integers: "); //prompts user for ints
int a = in.nextInt();
int b = in.nextInt();
int sum = 0;
for (int j = a; j <= b; j++)
{
if (j % 2 == 1)
sum += j;
}
System.out.println("The sum of all odd numbers (inclusive) between " + a + " and "+ b + " is " + sum);
}
}
int temp;
if(a > b) {
temp = a;
a = b;
b = temp;
}
Put this right before your for loop starts.
The if checks whether a (the first number entered) is larger than b. If it is, it swaps a and b. Now your for loop will always start with the smallest number and iterate up to the larger number (because after this if, a will always be the smaller number).
Using this method has the added side effect of making your output make sense. Your output will now always say: "between [smaller number] and [larger number]".
rolfl's answer is more elegant and works perfectly fine, but when the user enters the larger number first, your output may look kind of weird: "between [larger number] and [smaller number]", etc.
You can get the smaller and larger inputs by using the Math.min() and Math.max functions....
for (int j = Math.min(a,b); j <= Math.max(a,b); j++) {
if (j % 2 == 1) {
sum += j;
}
}
It's not working because A is larger than B in the for loop, you have it iterate while A is less than or equal to B.
You could do what nhgrif says but it's changing your data.. But he is correct.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.
Actually you should do the following 2 things:
1 It is just just like rolfl mentioned above. You need to put the min and max in the right place in loop.
for (int j = Math.min(a,b); j <= Math.max(a,b); j++)
{
if (j % 2 == 1) {
sum += j;
}
}
2 Use if (j % 2 == 1) it is not enough to check whether the num is odd.
e.g.
a = -5, b =0;
What will be the result?
int sum = 0;
for(int j=-5;j<0;j++)
{
if(j%2 == 1)
{
sum+=j;
}
}
The value for sum will be 0.
We need to change the condition to if(!(j%2 == 0)) Then you will get the expected result.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.