Error void type not allowed here

When I try to compile this: import java.awt.* ; class obj { public static void printPoint (Point p) { System.out.println ("(" + p.x + ", " + p.y + ")"); ...

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?

Mark Rotteveel's user avatar

asked Mar 14, 2010 at 15:45

David's user avatar

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

answered Mar 14, 2010 at 15:48

Justin Ethier's user avatar

Justin EthierJustin Ethier

130k51 gold badges227 silver badges284 bronze badges

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

answered Mar 14, 2010 at 15:47

Andrew Hare's user avatar

Andrew HareAndrew Hare

340k71 gold badges636 silver badges631 bronze badges

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.

answered Mar 14, 2010 at 15:48

Ben Zotto's user avatar

Ben ZottoBen Zotto

69.7k23 gold badges140 silver badges204 bronze badges

You are passing the result of printPoint() — which is void — to the println() function.

answered Mar 14, 2010 at 15:47

Carl Manaster's user avatar

Carl ManasterCarl Manaster

39.6k17 gold badges101 silver badges155 bronze badges

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.

Sam R.'s user avatar

Sam R.

15.9k11 gold badges68 silver badges121 bronze badges

answered Mar 14, 2010 at 15:53

ggf31416's user avatar

ggf31416ggf31416

3,5321 gold badge25 silver badges26 bronze badges

You probably wanted to do : printPoint (blank);. Looks like you are trying to print twice; once inside printPoint() and once inside main().

answered Mar 14, 2010 at 15:55

fastcodejava's user avatar

fastcodejavafastcodejava

39.2k27 gold badges131 silver badges184 bronze badges

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

answered May 5, 2022 at 1:02

Rohan Gupta's user avatar

  1. What Is the void type not allowed here Error?
  2. Fix Void Type Not Allowed Here Error in Java — Don’t Print in main() Method
  3. Fix Void Type Not Allowed Here Error in Java — Return a String Instead of Printing in printMessage1()

Fix Void Type Not Allowed Here Error in Java

We use many functions when creating big programs in Java, and sometimes errors might appear. One of the errors that the compiler can throw is the void type not allowed here error discussed in this article.

What Is the void type not allowed here Error?

We create a function in Java by writing the access modifier, a return type, a function name with parentheses, and the function body is enclosed with curly braces. We can return several types of data from a function, but when we don’t want to return any, we use the keyword void to tell the compiler that we don’t want to return anything from the method.

In the program below, we have a class JavaExample that contains two methods, first is the main() function, and the second is the printMessage1() that has a print statement System.out.println() that prints a message that printMessage1() receives as a parameter.

The function printMessage1() doesn’t return anything and just prints a message; we use void type as the return type. We use another print statement but in the main() method and call the printMessage1() function inside it with String 1 as an argument.

When we run the code, the output throws an error, void type not allowed here. It happens because printMessage1() already has a print statement that prints the value, and it doesn’t return anything when we call the function in a print statement; there’s nothing to print in the main method.

public class JavaExample {
    public static void main(String[] args) {

        System.out.println(printMessage1("String 1"));

    }

    static void printMessage1(String value) {
        System.out.println(value);
    }

}

Output:

java: 'void' type not allowed here

Fix Void Type Not Allowed Here Error in Java — Don’t Print in main() Method

The first solution to this error is that we do not call the function printMessage1() in a print statement because there is already a System.out.println() statement in the method itself, and it does not return anything.

In this code, we write the printMessage1() function’s body as a println() statement. We call the printMessage1() method in main() with a string as an argument.

public class JavaExample {
    public static void main(String[] args) {

       printMessage1("String 1");

    }

    static void printMessage1(String value) {
        System.out.println(value);
    }

}

Output:

Fix Void Type Not Allowed Here Error in Java — Return a String Instead of Printing in printMessage1()

The second solution is to specify a return type in the function, return a value, and print it wherever we call the function.

We write the method printMessage1() but with a return type String. Inside the method’s body, we use the return keyword with the value we want to return when called. In the main() method, we call the function printMessage1() into a print statement, but there will be no error as the method returns a value.

public class JavaExample {
    public static void main(String[] args) {

        System.out.println(printMessage1("How are you doing today?"));
        System.out.println(printMessage1("String 2"));

    }

    static String printMessage1(String value) {
        return value;
    }

}

Output:

How are you doing today?
String 2

Когда я пытаюсь скомпилировать это:

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

Я получаю эту ошибку:

obj.java:12: 'void' type not allowed here
        System.out.println (printPoint (blank)) ; 
                                               ^
1 error

Я действительно не знаю, как начать спрашивать об этом, кроме как спросить:

  • Что здесь пошло не так?
  • Что означает это сообщение об ошибке?

6 ответы

Если метод возвращает void то печатать нечего, отсюда и это сообщение об ошибке. Поскольку printPoint уже выводит данные на консоль, вам нужно просто вызвать его напрямую:

printPoint (blank); 

ответ дан 14 мар ’10, в 15:03

Вы пытаетесь распечатать результат printPoint который ничего не возвращает. Вам нужно будет изменить свой код, чтобы выполнить одно из этих двух действий:

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

или это:

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

ответ дан 14 мар ’10, в 15:03

Проблема типа в том, что println принимает строку для печати, но вместо строки вы вызываете printPoint метод, который возвращается void.

Вы можете просто позвонить printPoint(blank); в вашей основной функции и оставьте все как есть.

ответ дан 14 мар ’10, в 15:03

Вы передаете результат printPoint() — что недействительно — println() функции.

ответ дан 14 мар ’10, в 15:03

printPoint печатает сам по себе, а не возвращает строку. Чтобы исправить этот звонок printPoint (пусто) без System.out.println.

Лучшей альтернативой может быть: make printPoint(Point p) вернуть строку (и изменить ее имя на что-то вроде FormatPoint), таким образом, метод может использоваться для форматирования точки для консоли, графического интерфейса, печати и т. д. вместо привязки к консоли.

Создан 09 фев.

Вы, наверное, хотели сделать: printPoint (blank);. Похоже, вы пытаетесь напечатать дважды; однажды внутри printPoint() и однажды внутри main().

ответ дан 14 мар ’10, в 15:03

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

java

or задайте свой вопрос.

Понравилась статья? Поделить с друзьями:
  • Error vocaloid lyrics
  • Error vmerror принтер
  • Error vixx скачать песню бесплатно
  • Error virustotal probably now is blocking our requests
  • Error virtualtablet hid driver is not connected