Variables & Types¶
In this lab you will parse a number (hours) from the command-line arguments and calculate the number of seconds in those hours. For example:
$ java HoursToSeconds 2
Number of seconds in 2 hour(s) is 7200
Remember: Don't copy-and-paste any code from here, get your fingers used to typing the code.
Step 1: Create a New Class With Entry Point¶
Create a new file, HoursToSeconds.java, and inside of that file, define a class
with the same name, HoursToSeconds, e.g.:
public class HoursToSeconds {
}
Create a new entry point method inside the class, e.g.:
public static void main(String[] args) {
}
Step 2: Calculate "Seconds Per Hour" Using an int Variable¶
Inside of the main method (the entry point), write code that creates an int
variable named hours and assign 1 to it.
int hours = 1;
Compute the number of seconds for those hours:
int hoursInSeconds = hours * // fill in the rest of this computation yourself!
Step 3: Print the Result¶
Using System.out.println(), print out the text "Number of seconds in 1 hour(s) is 3600",
but replace the 1 with the value from the hours variable, and the 3600 with the
calculated number of seconds.
Remember to Use String Concatenation
For example: to print "I have worked here for 2 years and 3 months", you might write:
int years = 2;
int months = 3;
System.out.println("I have worked here for " + years + " years and " + months + " months");
Step 4: Compile and Run¶
Save the file HoursToSeconds.java, compile it, and then run it, e.g.:
$ java HoursToSeconds
Number of seconds in 1 hour(s) is 3600
Step 5: Parse Hours from the Command Line¶
Now let's get the number of hours from the command line arguments, instead of "hard-coding" it.
Replace the int hours = 1; with int hours = and use the Integer.parseInt()
method to convert the first command-line argument from a String to an int,
storing it in the hours variable.
JavaDoc
See the JavaDoc for parseInt: https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#parseInt-java.lang.String-int-
Everything else should remain the same, so do the same routine:
- Save your changes
- Compile the Java file
- Run it and pass a number as a parameter:
$ java HoursToSeconds 2 Number of seconds in 2 hour(s) is 7200
Experiment¶
Things to try:
- What if you don't pass anything on the command-line?
- What if the String isn't a valid number?
- What if the String isn't an integer (i.e., decimal)?
- What else might you try?
References¶
The JavaDoc API home page is here: https://docs.oracle.com/javase/8/docs/api
The Google Java Coding Style Guide can be found here: https://google.github.io/styleguide/javaguide.html
Once you've completed the above steps, check in with the instructor to review your code.
Once you've completed the above steps, check in with the instructor to review your code.