Skip to content

Commit cffe737

Browse files
committed
Add WhyMethods example code
1 parent 27c3a9f commit cffe737

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/com/codefortomorrow/intermediate/chapter11/examples/Methods.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22

33
public class Methods {
44
public static void main(String[] args) {
5+
// prints "Hello World" 5 times
56
for (int i = 0; i < 5; i++) {
67
printMessage();
78
}
89
}
910

11+
/** Prints "Hello World" */
1012
public static void printMessage() {
1113
System.out.println("Hello World");
1214
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.codefortomorrow.intermediate.chapter11.examples;
2+
3+
import java.util.Scanner;
4+
5+
public class WhyMethods {
6+
public static void main(String[] args) {
7+
// cleaner code because methods group actions
8+
printMessages();
9+
printSum();
10+
}
11+
12+
/** Prints 3 messages */
13+
public static void printMessages() {
14+
System.out.println("May the Force be with you");
15+
System.out.println("Tahiti, it's a magical place");
16+
System.out.println("Live long and prosper");
17+
}
18+
19+
/** Prints the sum of 2 numbers */
20+
public static void printSum() {
21+
Scanner input = new Scanner(System.in);
22+
23+
// prompt user to enter 2 numbers
24+
System.out.print("Enter number 1: ");
25+
double num1 = input.nextDouble();
26+
System.out.print("Enter number 2: ");
27+
double num2 = input.nextDouble();
28+
29+
double sum = num1 + num2;
30+
31+
// print the sum of those numbers
32+
System.out.println("Sum: " + sum);
33+
34+
input.close();
35+
}
36+
}

0 commit comments

Comments
 (0)