Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

method will recurse infinitly

a super silly question but why does the method prime recurse infinitely ?
this is a simple java code where i’m trying to make a method i can call to get the prime of parameter x , but it tells me that the method will recurse infinitely , i tried copy pasting the code of the prime method to the main method and it worked well , so can someone help please?

`

import java.util.*;

public class Mavenproject2 {

    static int prime(int x) {
        boolean f = true;
        if (x == 1 || x == 0) {
            f = false;
        } else {

            for (int i = 2; i < x; i++) {
                if (x % i == 0) {
                    f = false;
                    break;
                }
            }
        }
        if (f) {
            System.out.println("prime");
        } else {
            System.out.println("not prime");
        }

        return prime(x);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("enter number");
        int x = input.nextInt();
        System.out.println(prime(x));

    }
}

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you just want to know if the number passed in is prime. You need to change your return type to a bool and return f.

You’re returning prime(x) which will keep calling into itself.

I would actually do something like this

import java.util.*;

public class Mavenproject2 {

    static string prime(int x) {
        boolean f = true;
        if (x == 1 || x == 0) {
            f = false;
        } else {

            for (int i = 2; i < x; i++) {
                if (x % i == 0) {
                    f = false;
                    break;
                }
            }
        }
        if (f) {
            return "prime";
        } 

        return "not prime";
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("enter number");
        int x = input.nextInt();
        System.out.println(prime(x));

    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading