'What causes "'void' type not allowed here" error
When I try to compile this:
import java.awt.* ;
class obj
{
public static void printPoint (Point p)
{
System.out.println ("(" + p.x + ", " + p.y + ")");
}
public static void main (String[]arg)
{
Point blank = new Point (3,4) ;
System.out.println (printPoint (blank)) ;
}
}
I get this error:
obj.java:12: 'void' type not allowed here
System.out.println (printPoint (blank)) ;
^
1 error
I don't really know how to start asking about this other than to ask:
- What went wrong here?
- What does this error message mean?
Solution 1:[1]
If a method returns void then there is nothing to print, hence this error message. Since printPoint already prints data to the console, you should just call it directly:
printPoint (blank);
Solution 2:[2]
You are trying to print the result of printPoint which doesn't return anything. You will need to change your code to do either of these two things:
class obj
{
public static void printPoint (Point p)
{
System.out.println ("(" + p.x + ", " + p.y + ")");
}
public static void main (String[]arg)
{
Point blank = new Point (3,4) ;
printPoint (blank) ;
}
}
or this:
class obj
{
public static String printPoint (Point p)
{
return "(" + p.x + ", " + p.y + ")";
}
public static void main (String[]arg)
{
Point blank = new Point (3,4) ;
System.out.println (printPoint (blank)) ;
}
}
Solution 3:[3]
The type problem is that println takes a String to print, but instead of a string, you're calling the printPoint method which is returning void.
You can just call printPoint(blank); in your main function and leave it at that.
Solution 4:[4]
You are passing the result of printPoint() - which is void - to the println() function.
Solution 5:[5]
printPoint prints by itself rather than returning a string. To fix that call printPoint (blank) without the System.out.println.
A better alternative may be: make printPoint(Point p) return a string (and change its name to something like FormatPoint), that way the method may be used to format a point for the console, GUI, print, etc rather than being tied to the console.
Solution 6:[6]
You probably wanted to do : printPoint (blank);. Looks like you are trying to print twice; once inside printPoint() and once inside main().
Solution 7:[7]
import java.awt.* ;
class Main
{
public static void printPoint (Point p)
{
System.out.println ("(" + p.x + ", " + p.y + ")");
}
public static void main (String[]arg)
{
Point blank = new Point (3,4) ;
printPoint (blank) ;
}
}
//you can't print the value while its not returnring anything in function try this one
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Justin Ethier |
| Solution 2 | |
| Solution 3 | Ben Zotto |
| Solution 4 | Carl Manaster |
| Solution 5 | Sam R. |
| Solution 6 | fastcodejava |
| Solution 7 | Rohan Gupta |
