X Tutup
Skip to content

Commit 19b329e

Browse files
committed
rough of chap1
1 parent 661e426 commit 19b329e

File tree

9 files changed

+338
-28
lines changed

9 files changed

+338
-28
lines changed

.vscode/settings.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"java.configuration.updateBuildConfiguration": "automatic"
3+
}

appendixa.adoc

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,34 @@
11

2+
[appendix]
3+
== Kris' Special Class
4+
5+
In this book, we use a simple template for all your early Java programs.
6+
Why?
7+
Well, in many books, tutorials, etcetera for Java, they use a very simple (well, for Java, simple) _Hello World_ program.
8+
9+
*blah, blah, blah*
10+
11+
But in this book, I use a special template. One that you should use when working thru the examples and exercises in this book.
12+
13+
=== The SPECIAL ZipCode java template!
14+
15+
``` Java
16+
public class ZipCode {
17+
18+
void compute() {
19+
20+
//Your code goes in here...
21+
22+
}
23+
24+
25+
// don't change this...
26+
public static void main(String args { new ZipCode().compute(); }
27+
}
28+
29+
// NOTICE the } in the previous line? it's crucial
30+
```
31+
232
[appendix]
333
== Advanced Ideas
434

consolelog.adoc

Lines changed: 93 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,39 @@ Perhaps the simplest Java program is:
44

55
[source]
66
----
7-
console.log("Hello, World!");
7+
public class Main {
8+
public static void main(String[] args) {
9+
System.out.println("Hello, World!");
10+
}
11+
}
812
----
913

10-
This program just prints "Hello, World!". footnote:[And while you might _not yet_ understand this _technical description_, it is a program of one _line_ of code, which says "call the 'log' method on the 'console' object, using the string "Hello, World!" as the argument to be logged."]
14+
This program just prints "Hello, World!".
1115

12-
Logging, in this case, means _outputting_ or _printing_ the "Hello, World!" somewhere. That somewhere is the _console_, a place Java uses to communicate with a user (in this case, us, the programmers.)
16+
_System.out.println_, in this case, means _outputting_ or _printing_ the "Hello, World!" somewhere. That somewhere is probably the terminal where the program was run.
1317

14-
(And if you haven't done it yet, go to https://code.zipcode.rocks and make a browser bookmark for yourself. Once that's done, you can use that REPL footnote:[a REPL is short for "read-evaluate-print loop", a special kind of computer program that lets you run code of a given language.] as a place where you can type in the code from this book and run it to see what each code snippet does.)
1518

16-
We will use `console.log` to do a lot in the coming pages. It's a simple statement, one that in other languages might be `print` or `write` or `puts` (and why we all cannot just agree on one way to do this, well, beats me. Java's is `console.log`)
19+
We will use `System.out.println` to do a lot in the coming pages. It's a simple statement, one that in other languages might be `print` or `write` or `puts` (and why we all cannot just agree on one way to do this, well, beats me. Java's is `System.out.println`)
1720

1821
Here's your second Java program:
1922

2023
[source]
2124
----
22-
let milesPerHour = 55.0;
23-
console.log("Car's Speed: ", milesPerHour);
25+
public class Main {
26+
public static void main(String[] args) {
27+
double milesPerHour = 55.0;
28+
System.out.println("Car's Speed: " + milesPerHour);
29+
}
30+
}
2431
----
2532

26-
If you typed into your REPL and clicked the "Run" button, you should have seen this as your output:
33+
Now, how do we `run` this program? Use a REPLI.it!!
2734

2835
****
29-
Car's Speed: 55
36+
> sh -c javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')
37+
> java -classpath .:target/dependency/* Main
38+
Car's Speed: 55.0
39+
>
3040
****
3141

3242
Cool, huh? The ability to communicate with you is one of Java's most fundamental capabilities. And you've run two Java programs. Congratulations, you're a coder. (Well, at least for today you are.)
@@ -41,18 +51,21 @@ Java will ignore anything on a line after two forward slashes. "//"
4151
[source]
4252
----
4353
// this is a comment. it might describe something in the code.
44-
console.log('Hello');
54+
int x = 53 - 11;
4555
46-
console.log('World'); // this is also a comment.
56+
int y = x * 4; // this is also a comment.
4757
----
4858

4959
Often, you'll see something like this in this book.
5060

5161
[source]
5262
----
53-
let flourAmount = 3.5;
54-
55-
console.log(flourAmount); // -> 3.5
63+
public class Main {
64+
public static void main(String[] args) {
65+
double flourAmount = 3.5;
66+
System.out.println(flourAmount); // -> 3.5
67+
}
68+
}
5669
----
5770

5871
That comment at the end of the console.log line is showing what you can expect to see in the output. Here it would be "3.5" printed by itself. Try it in your bookmarked Repl.
@@ -61,22 +74,45 @@ We can also add useful stuff to the .log call.
6174

6275
[source]
6376
----
64-
let flourAmount = 3.5;
65-
66-
console.log("We need", flourAmount, "cups of flour."); // -> We need 3.5 cups of flour.
77+
public class Main {
78+
public static void main(String[] args) {
79+
double flourAmount = 3.5;
80+
System.out.println("We need " + flourAmount + " cups of flour."); // -> 3.5
81+
}
82+
}
6783
----
6884

6985
See how Java types it all out as a useful phrase? That proves to be very handy in a million-plus (or more) cases.
7086

7187
Comments can be used to explain tricky bits of code, or describe what you should see in output. Comments are your friend.
7288

89+
== BUT WAIT!!!
90+
91+
What does `int` and `double` signify? Well, see how they proceed another word?
92+
93+
[source]
94+
----
95+
public class Main {
96+
public static void main(String[] args) {
97+
double flourAmount = 3.5;
98+
// ^^^^^^ ^^^^^^^^^^^
99+
System.out.println("We need " + flourAmount + " cups of flour."); // -> 3.5
100+
}
101+
}
102+
----
103+
104+
It is our way of telling Java what `flourAmount` is. We want `flourAmount` to be place holder for the number `3.5`, because makes
105+
the code easier to read and understand. See much more on this, up ahead, in `variables`.
106+
107+
Oh, and `int`?? Well, it means a number, but just an integer like 0, 1, 2, 42, 99, etc. A `double` can have decimal point and some number after, so I can write `3.5` or `42.0`.
108+
73109
== Statements and Expressions
74110

75111
In Java, there are parts of a program and different parts have different names. Two of the most basic (and fundamental) are *statements* and *expressions*.
76112

77113
=== Expressions
78114

79-
An *expression* is something that needs to be computed to find out the answer. Here are a few simple ones.
115+
An *expression* is something that needs to be _computed_ to find out the answer. Here are a few simple ones.
80116

81117
[source]
82118
----
@@ -87,26 +123,34 @@ speed > 55.0
87123
regularPrice * (1.0 - salePercentOff)
88124
----
89125

90-
Each of these lines is something we'd like Java to *compute* for us. That computation is often referred to as "evaluation" or "evaluate the expression" to get to the answer. There are two kinds of expressions in Java, _arithmetic expressions_ and _boolean expressions_.
126+
Each of these lines is something we'd like Java to *compute* for us. That computation is often referred to as "evaluation" or "evaluate the expression" to get to the answer.
127+
There are two kinds of expressions in Java, _arithmetic expressions_ and _boolean expressions_.
91128

92-
*Arithmetic expressions* are, as their name implies, something that require arithmetic to get the answer. An expression like "5 + 8 - 3" gets _evaluated_ to 10.
129+
*Arithmetic expressions* are, as their name implies, something that require arithmetic to get the answer. An expression like "5 + 8 - 3" gets _evaluated_ to 10.
130+
So an arithmetic expression will end up being a _number_.
93131

94-
*Boolean expressions* result in either a True or a False value. Example: "maxSpeed > 500.0" - this is either true or false depending on the value of maxSpeed.
132+
*Boolean expressions* result in either a True or a False value.
133+
Example: "maxSpeed > 500.0" - this is either true or false depending on the value of maxSpeed.
134+
Or "homeTeamScore > visitorTeamScore" which will be true is and only if the Home team's score is greater than
135+
the Visitor team's score. Both _scores_ are numbers, the result of the **greater than** makes the result of the
136+
epxression a _boolean expression_ (either **true** or **false**).
95137

96138
=== Statements
97139

98140
A *statement* is just a line of Java. It ends with a ';' (semi-colon).
99141

100142
[source]
101143
----
102-
// at the Grocery
103-
104-
salesTaxRate = 0.06;
144+
public class Main {
145+
public static void main(String[] args) {
146+
// at the Grocery
105147
106-
totalGroceries = 38.99;
107-
salesTax = totalGroceries * salesTaxRate;
108-
109-
chargeToCard = totalGroceries + salesTax;
148+
double salesTaxRate = 0.06;
149+
double totalGroceries = 38.99;
150+
double salesTax = totalGroceries * salesTaxRate;
151+
double chargeToCard = totalGroceries + salesTax;
152+
}
153+
}
110154
----
111155
And this is what a Java program looks like. It's just a list of statements, one after the other, that get computed from the top down.
112156

@@ -144,3 +188,24 @@ if (magePower > 120.0) {
144188

145189
See those curly-braces? They start and stop the _block_, and contain the statements within. You can also see how the code is indented, but the real key are those braces. You'll see lots of blocks when you're looking at Java code.
146190

191+
And, it's a bad idea, but this code:
192+
193+
[source]
194+
----
195+
if (wizardStrength > 120.0) { maxMagic = Wizard.maxpower(); lifeSpan = Wizard.maxlife(); maxWeapons = wizardStrength * numberOfWands; }
196+
----
197+
198+
is identical to this:
199+
200+
[source]
201+
----
202+
if (wizardStrength > 120.0) {
203+
maxMagic = Wizard.maxpower();
204+
lifeSpan = Wizard.maxlife();
205+
maxWeapons = wizardStrength * numberOfWands;
206+
}
207+
----
208+
209+
But the SECOND example is formatted much cleaner, making it more readable and therefore easier to understand.
210+
211+

src/zipcode/pom.xml

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
3+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>zipcode</groupId>
8+
<artifactId>zipcode</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<name>zipcode</name>
12+
<!-- FIXME change it to the project's website -->
13+
<url>http://www.example.com</url>
14+
15+
<properties>
16+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
17+
<maven.compiler.source>11</maven.compiler.source>
18+
<maven.compiler.target>11</maven.compiler.target>
19+
</properties>
20+
21+
<dependencies>
22+
<dependency>
23+
<groupId>junit</groupId>
24+
<artifactId>junit</artifactId>
25+
<version>4.11</version>
26+
<scope>test</scope>
27+
</dependency>
28+
</dependencies>
29+
30+
<build>
31+
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
32+
<plugins>
33+
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
34+
<plugin>
35+
<artifactId>maven-clean-plugin</artifactId>
36+
<version>3.1.0</version>
37+
</plugin>
38+
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
39+
<plugin>
40+
<artifactId>maven-resources-plugin</artifactId>
41+
<version>3.0.2</version>
42+
</plugin>
43+
<plugin>
44+
<artifactId>maven-compiler-plugin</artifactId>
45+
<version>3.8.0</version>
46+
</plugin>
47+
<plugin>
48+
<artifactId>maven-surefire-plugin</artifactId>
49+
<version>2.22.1</version>
50+
</plugin>
51+
<plugin>
52+
<artifactId>maven-jar-plugin</artifactId>
53+
<version>3.0.2</version>
54+
</plugin>
55+
<plugin>
56+
<artifactId>maven-install-plugin</artifactId>
57+
<version>2.5.2</version>
58+
</plugin>
59+
<plugin>
60+
<artifactId>maven-deploy-plugin</artifactId>
61+
<version>2.8.2</version>
62+
</plugin>
63+
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
64+
<plugin>
65+
<artifactId>maven-site-plugin</artifactId>
66+
<version>3.7.1</version>
67+
</plugin>
68+
<plugin>
69+
<artifactId>maven-project-info-reports-plugin</artifactId>
70+
<version>3.0.0</version>
71+
</plugin>
72+
</plugins>
73+
</pluginManagement>
74+
</build>
75+
</project>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
public class %s {
2+
3+
void compute() {
4+
//Your code goes in here...
5+
}
6+
7+
// don't change this...
8+
public static void main(String args { new %s().compute(); }
9+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package zipcode;
2+
3+
import java.io.IOException;
4+
import java.io.PrintWriter;
5+
import java.nio.file.Files;
6+
import java.nio.file.Path;
7+
import java.util.ArrayList;
8+
import java.util.Collections;
9+
import java.util.HashMap;
10+
import java.util.Map;
11+
import java.util.concurrent.ConcurrentHashMap;
12+
13+
public enum Command {
14+
CLASSNEW("classcreate"){
15+
public void execute(String[] args) {
16+
final Path filePath = Path.of("./","ClassTempl.txt");
17+
String templ;
18+
try {
19+
templ = Files.readString(filePath);
20+
String classname = args[0];
21+
String classfilename = classname+".java";
22+
PrintWriter result = new PrintWriter(classfilename);
23+
result.printf(templ, classname, classname);
24+
} catch (IOException e) {
25+
// TODO Auto-generated catch block
26+
e.printStackTrace();
27+
}
28+
}
29+
},
30+
ERR("error"){
31+
public void execute(String[] args) {
32+
}
33+
},
34+
35+
;
36+
37+
public static Command getOp(String string) {
38+
return null;
39+
}
40+
41+
abstract void execute(String[] args);
42+
43+
private String name;
44+
private static Boolean _DEBUG = false;
45+
46+
private static final Map<String,Command> ENUM_MAP;
47+
48+
Command (String name) {
49+
this.name = name;
50+
}
51+
52+
public String getName() {
53+
return this.name;
54+
}
55+
56+
// Build an immutable map of String name to enum pairs.
57+
// Any Map impl can be used.
58+
59+
static {
60+
Map<String,Command> map = new ConcurrentHashMap<String, Command>();
61+
for (Command instance : Command.values()) {
62+
map.put(instance.getName().toLowerCase(),instance);
63+
}
64+
ENUM_MAP = Collections.unmodifiableMap(map);
65+
}
66+
67+
public static Command get (String name) {
68+
return ENUM_MAP.getOrDefault(name.toLowerCase(), Command.ERR);
69+
}
70+
71+
}

0 commit comments

Comments
 (0)
X Tutup