What does Incompatible types: void cannot be converted to ... mean?
Quick answer
The compiler is telling you that your code is trying to use the "result" of a method that doesn't return a result.
Solution:
Read the javadoc for the method you are trying to call (or the source code if you don't have javadocs).
From the javadocs (or source code), work out how the method should really be used.
Correct your code to either not use the (non-existent) result, or to use a different method. Alternatively, if it is one of your methods that you are calling, another possible correction might be to change the method to return an appropriate value.
Detailed example
Consider this example:
public class Test {
private static void add(int a, int b) {
int res = a + b;
}
public static void main(String[] args) {
int sum = add(1, 1);
}
}
When I compile this using javac
(Java 8), I get the following compilation error.
$ javac Test.java
Test.java:7: error: incompatible types: void cannot be converted to int
int sum = add(1, 1);
^
1 error
The compilation error is actually telling us a few things:
The compiler has detected a problem at the indicated position on the indicated line in the
main
method. The root cause of the problem is not necessarily on that line, but that is where the compiler has figured out that something is wrong.It is a type error - hence the "incompatible types" phrase.
The incompatibility involves two types:
void
andint
.The compiler thinks that the code requires a conversion from
void
toint
... and that is not possible.
So what is this void
type?
Well, you will most likely have learned that Java supports two kinds of type: primitive types and reference types. The void
type is not either of these. It is the "type" that means "there is no value". (If you consider types to be sets of values, then void
is the empty set.)
The primary use for the void
type is used is in method declarations. Look at the declaration of the add
method above. Notice that we have declared add
with the signature:
private static void add(int a, int b)
That signature states that the add
method takes two int
methods, and returns void
. That means that the method will return nothing.
Yet ... we have called it like this:
int sum = add(1, 1);
This is expecting the add
call to return an int
value that we will assign to sum
.
This is what the "void cannot be assigned to ..." error message really means. The compiler is telling us that code is trying to use the result of a method that has been declared to return no result. That's not possible. The Java language does not allow you to "pull a value out of the air" to use.
There are potentially two ways to make the compilation error go away:
We could change the declaration of the method so that it does return a value. For example:
private static int add(int a, int b) {
int res = a + b;
return res;
}We could change the call site so that it does not attempt yo use the (non-existent) return value. For example:
add(1, 1);
In this example, either approach would do that. But only one approach (the first one) makes the code work as intended.
incompatible types: void cannot be converted to int
Your program does not have to return an int
in public static int main
. Instead you can have it as void
(meaning don't return anything). You should simply just print your statements and don't return
them. Also the int[]
should be String[]
and Scanner
should check for nextInt()
as pointed out in comments!
import java.util.InputMismatchException;
import java.util.Scanner; // This will import just the Scanner class.
public class GuessAge {
public static void main(String[] args) {
System.out.println("\nWhat is David's Age?");
Scanner userInputScanner = new Scanner(System.in);
int age = userInputScanner.nextInt();
int validInput = 20;
// typo in your code - compare to age
if (validInput == age) {
System.out.println("Correct!!");
}
else {
System.out.println("Wrong....");
}
}
}
Forcing something to be destructed last in C++
You could use the Observer pattern. A Controller communicates to it's supervisor that it's being destroyed. And the Supervisor communicates the same to it's child upon destruction.
Take a look at http://en.wikipedia.org/wiki/Observer_pattern
Java error: void cannot be converted to String
Your function has no return value void
and you try to assign it to a string variable, that is what the error message means.
So change:
public static void encrypt(String original) throws Exception {
to
public static String encrypt(String original) throws Exception {
and
return sb.toString()
So the class looks like:
class MD5Digest {
public static String encrypt(String original) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("original:" + original);
System.out.println("digested:" + sb.toString());
return sb.toString();
}
}
BTW: Take care of Java's naming convention. Class names should be subjects.
EDIT:
Because your encrypt message throws an exception, you have to throw the exception also in public static void main(String []args) throws Exception{
or you have to handle it in a try-catch-block
error: incompatible types: void cannot be converted to double
System.out.print()
returns no value; it has a return type of void
.
In order to rewrite this without any errors, change it to something like this:
public static void generateReport(double sqft, double gallonCost, int numGallons, double hoursLabor, double paintCost, double laborCost, double totalCost) {
System.out.print("To paint" + sqft + "square feet, with");
System.out.print("paint that costs" + gallonCost + "per gallon,");
System.out.print("you will need" + numGallons + "gallons of paint");
System.out.print("and" + hoursLabor + "hours of labor.");
System.out.print("The cost of the paint is: " + paintCost );
System.out.print("The cost of the labor is: "+ laborCost);
System.out.print("The total cost of the job is: " + totalCost);
System.out.println();
Related Topics
How to Find a Button Source in Awt (Calculator Homework)
Using Threads to Make Database Requests
Netbeans Gui Editor Generating Its Own Incomprehensible Code
Quality of Image After Resize Very Low - Java
Variable Used in Lambda Expression Should Be Final or Effectively Final
How to Convert Byte Array to String and Vice Versa
Replace a Character At a Specific Index in a String
Get a List of Resources from Classpath Directory
How to Import an Existing X.509 Certificate and Private Key in Java Keystore to Use in Ssl
Unicode Equivalents For \W and \B in Java Regular Expressions
Getting a File'S Md5 Checksum in Java
Why Can't I Do Assignment Outside a Method
Initialization of an Arraylist in One Line
Adding External Library to Artifact Jar in Intellij Idea
Should I Always Use a Parallel Stream When Possible
How to Loop Through a Hashmap in Jsp