Reputation: 11
I have no problem using a method int to run this program; however I wanted to be able to learn how to do the void
method.
I know the return
statement isn't necessary in void
, and for void
with two int
parameters. In my book it said parameters should be written as (int a, int b)
.
However, in my code for lines 16 and 17
sum = computeSum(num1, num2);
product = computeProduct(num1, num2);)
I get the error incompatible types, void cannot be converted to int
.
How do I rectify this for future reference? Thanks so much!
import java.util.Scanner;
public class Lab6
{
public static void main (String [] args)
{
//create a scanner object for receiving user input
Scanner keyboard = new Scanner (System.in);
int num1, num2, sum, product;
System.out.println ("Please enter an integer: ");
num1 = keyboard.nextInt();
System.out.println ("Please enter another integer: ");
num2 = keyboard.nextInt();
sum = computeSum(num1, num2);
product = computeProduct(num1, num2);
}
public static void computeSum(int num1, int num2)
{
int sum = 0;
sum = num1 + num2;
System.out.println ("The sum of your integers is " + sum);
}
public static void computeProduct(int num1, int num2)
{
int product = 0;
product = num1 * num2;
System.out.println("\nThe product of your integers is: " + product);
}
}
Upvotes: 0
Views: 2497
Reputation: 1279
Steve Bourne proposed that Algol68's VOID be defined as MODE VOID = STRUCT()
. When Steve arrived at Bell Labs he talked Dennis into adding void as a type in C. It saved the instruction loading register for return value. Also when Steve got to the lab C types were like PL/1 namely offsets from any base you liked. They changed to A68 types but be the specific reason for this change is now lost. A few other A68isms ended up in C.
Speculation: Std C could have considered typedef struct{}void
...
Upvotes: 1
Reputation: 347194
As you said, void
methods don't return a value, so sum = computeSum(num1, num2);
makes no sense, as computeSum
doesn't return anything.
You should try using...
computeSum(num1, num2);
computeProduct(num1, num2);
instead...
Upvotes: 1
Reputation: 117589
The method computeSum()
's return type is void
, i.e. it returns nothing which means it cannot be assigned to a variable. Hence, the following is not possible:
sum = computeSum(num1, num2);
Upvotes: 2