Home > Net >  method will recurse infinitly
method will recurse infinitly

Time:12-18

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));

    }
}

`

CodePudding user response:

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));

    }
}
  • Related