Вы находитесь на странице: 1из 3

HIT2037 Lab1 Warm up

Lab1 Warm up
In this exercise we will write a simple method/function in Java. In 1a and 1b the your code will provide two numbers and you will create two functions to calculate and print the total.

1a Step1) Create a file called SimpleFunctionWithStatic.java. Step2) Copy and paste the following code. public class SimpleFunctionWithStatic{ public static void main(String args[]){ int total; printTotal(1,2); total = calculateTotal(1,2); System.out.println("The total is " + total); } public static void printTotal(int num1, int num2){ int result = num1 + num2; System.out.println("Total is " + result); } public static int calculateTotal(int num1, int num2){ int result = num1 + num2; return result; } } Step3) Compile the code in the command prompt using the following command: javac SimpleFunctionWithStatic.java Make sure there are no errors on Step3 then proceed to Step4. Step4) Run the code using the following command java SimpleFunctionWithStatic.java Step5) You should see the following output Total is 3 The total is 3

I Mohd-Sarkawi 22/2/2011

HIT2037 Lab1 Warm up

1b Lets modify the code in 1a Step1) Create another file called SimpleFunctionNoStatic.java Step2) Copy and paste the following code public class SimpleFunctionNoStatic{ public static void main(String args[]){ int total; SimpleFunctionNoStatic s = new SimpleFunctionNoStatic(); s.printTotal(1,2); total = s.calculateTotal(1,2); System.out.println("The total is " + total); } public void printTotal(int num1, int num2){ int result = num1 + num2; System.out.println("Total is " + result); } public int calculateTotal(int num1, int num2){ int result = num1 + num2; return result; } } Compile and run the code.

I Mohd-Sarkawi 22/2/2011

HIT2037 Lab1 Warm up

1c In this exercise we will require the user to key in two numbers. Step1) Create another file called SimpleFunctionScanner.java Step2) Copy and paste the following code
import java.util.Scanner; public class SimpleFunctionScanner{ public static void main(String args[]){ int total; int number1, number2; Scanner sc = new Scanner(System.in); System.out.print("Enter Number1: "); number1 = Integer.parseInt(sc.nextLine()); System.out.print("Enter Number2: "); number2 = Integer.parseInt(sc.nextLine()); SimpleFunctionScanner s = new SimpleFunctionScanner (); s.printTotal(number1, number2); total = s.calculateTotal(number1, number2); System.out.println("The total is " + total); } public void printTotal(int num1, int num2){ int result = num1 + num2; System.out.println("Total is " + result); } public int calculateTotal(int num1, int num2){ int result = num1 + num2; return result; } }

Compile and run the code. You should get the following output: Enter Number1: 20 Enter Number2: 30 Total is 50 The total is 50

I Mohd-Sarkawi 22/2/2011

Вам также может понравиться