Vi Pshnchk
Vi Pshnchk

Reputation: 127

Call to void method with parameters in Java

I am calling the void method

printDivisors(inputNum)

and getting this error:

'void' type not allowed here

I concatenate the call to the method in a string and the compiler keeps complaining...

Here is the call to a method in a code:

if (determinePrime(inputNum)) {
    JOptionPane.showMessageDialog(null, "Prime");
} else {
    JOptionPane.showMessageDialog(null, "Not Prime" + printDivisors(inputNum));
}

Below you can see the full program:

import javax.swing.JOptionPane;
    public class method_01 {
    public static void main (String [] args) {
        String input;
        int inputNum;

        // Determine Prime

        do {
            input = JOptionPane.showInputDialog("Enter a positive number please");
            inputNum = Integer.parseInt(input);
        } while (inputNum < 1 );

        if (determinePrime(inputNum)) {
            JOptionPane.showMessageDialog(null, "Prime");
        } else {
            JOptionPane.showMessageDialog(null, "Not Prime" + printDivisors(inputNum));
        }
    }

    // Determine Prime Method

    public static boolean determinePrime(int num) {

        for (int i = 2; i < num ; i++) {
            if (num % i == 0) 
                return false;
        }
        return true;
    }

    // Print all the divisors of a number

    public static void printDivisors(int number) {

        for (int i = 1; i <= number; i++ ) {

            if (number % i == 0)

                System.out.print("\t" + i); 
        }
    }
}

Any help would be greatly appreciated.

Upvotes: 1

Views: 6525

Answers (2)

Ivan Ling
Ivan Ling

Reputation: 117

Your declaration is void here:

public static void printDivisors(int number)

If you are using it inside the function, you should return a string instead. i.e. write to a string instead of

System.out.print("\t" + i);

and use + to append the string at the end of your code:

JOptionPane.showMessageDialog(null, "Not Prime" + printDivisors(inputNum));}

Upvotes: 3

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

The problem is in

JOptionPane.showMessageDialog(null, "Not Prime" + printDivisors(inputNum));

I suppose you are trying to print the divisor, but it returns null so ideally, when the compiler compiles, it searches for a value, as you have " + " sign after "Not Prime", but does not get anything. thus it is throwing an exception.

either change the return type of printDivisors method or remove that part from the parameter.

Upvotes: -1

Related Questions