"type mismatch: cannot convert from int to byte"
new to Java and so far struggling a lot.. tried all day to fix this error yesterday and to no avail… any help will be appreciated.
import java.util.Random; import java.util.Date; class Proj06{ public static void main(String[] args){ Random generator = null; if(args.length != 0){ generator = new Random(Long.parseLong(args[0])); }else{ generator = new Random(new Date().getTime()); }; //Get and save positive random number of type int. int valA = Math.abs((generator.nextInt()))/67000 + 1024; Proj06Runner obj = new Proj06Runner(); String valB = obj.run("certificaton"); String valC = obj.run(1,"name"); byte valD = obj.run(valA); //Print the original random integer System.out.println(valA); //Print the three values returned from the three calls // to the run method. System.out.println(valB); System.out.println(valC); System.out.println(valD); //Print the original random integer after casting it // down to type byte. //System.out.println((byte)valA); }//end main public class Proj06Runner extends Proj06{ public int run(int valA){ return valA; } public String run(String valB){ return "this works"; } public String run(int i, String valC){ return "this also works"; } //this does not work public byte run(byte valD){ return valD; } }
I can’t change anything in main..i know there’s an error with how valA is an int but i’m assigning it to a byte variable
Your Proj06Runner class has these two methods:
public int run(int valA){ return valA; } public byte run(byte valD){ return valD; }
First one takes an int
and returns an int
. The second one takes a byte
and returns a byte
. You are calling the first one. I suspect you expected to call the second one, but that will not work because the main
method is passing an int
as the parameter.
One way to fix the compiler error is to "merge" these two methods into one method that takes an int
and returns a byte
. For example:
public byte run(int valD){ return (byte) valD; }