Getting familiar with Java.
This is an individual assignment. Make sure first that you can log in to the CS machines.
public class HelloWorld { }
(Remember that in Java, your class and your compilation unit (the file) must have exactly the same name: capitalization and everything.)
HelloWorld
class, add a main method by typing the code:
public static void main(String[] args) { }
(Similar to Python, main
is a special name with a special declaration. The main
method is where your program's execution will begin.)
main
method, add code that will print out a greeting message:
System.out.println("Hello, World!");
$ javac HelloWorld.java $ java HelloWorld Hello, World!
Note: unlike Python, Java is a compiled language. Therefore, before you execute your program, you have to compile it using javac
(“Java Compiler”). This converts your HelloWorld.java
code into a HelloWorld.class
file that contains the machine-language version of your program that can run on a Java Virtual Machine (VM). Then, you run java
(the Java VM) and give it the name of your class that it will execute. The practical implication of this is that any time you alter your code, to run the updated version you will need to run both javac
and java
again.
Now you'll write a guessing game in Java.
Create a new file Guess.java
, in which you define the class Guess
.
Inside of class Guess
, write a program that will:
Math.random()
or java.util.Random
).The Java language constructions that you will need to use can be found in Appendix A of the book. Use of the Scanner
class (for input) is in Section A.32, Math
methods are in Section A.30, loop constructs are A.58, etc.
Submit your two Java files — “HelloWorld.java” and “Guess.java” — by zipping them up into hw2.zip
, then uploading them to Moodle. Make sure that your zip file contains only these two files (copy it somewhere else on your computer and open it to check): no directories and no extraneous stuff please.
Start early, ask lots of questions, and have fun!