In your introduction to Java, you probably used the Scanner
class to facilitate reading keyboard input. You may have used such Scanner
methods as readLine()
and readInt()
. In this exercise, we'll use this class to do a slightly sophisticated version of a simple task.
Here's the task: read in two numbers, then compute and print their sum. A run of your program would look something like this (user's text in red):
Enter two numbers: 4 5 The sum of 4 and 5 is 9.
However, there is one
small twist: your program should let the user silently decide whether to enter
numbers as integers or floating-point numbers (or, in Java terms, as
int
or as
double
). And then your program should calculate and display the sum depending on the type of the user's input. So your program should also run like this:
Enter two numbers: 4.2 5.45 The sum of 4.2 and 5.45 is 9.65.
Of course, your program should be able to deal with "mixed types":
Enter two numbers: 5 17.3 The sum of 5 and 17.3 is 22.3.
So the type of the output matches the type of the input—if both input values can be treated as int
, then the output is an int
; otherwise the output is a double
.
The Scanner
class contains all the methods you need to do this easily. To learn more about how it works, visit the official API documentation. Note! A lot of this documentation is written for very experienced Java programmers (I don't fully understand all of it). This is something you should get used to: getting useful information out of documentation that you don't fully understand. See what you can get out of the introductory description of the class (there are some valuable hints in the example code, which uses methods nextInt()
, hasNextLong()
, and nextLong()
—make sure you understand what these methods do), then scroll down and see else is provided in the documentation. See if you can find documentation for the methods you know about—is there anything there that's new to you? Are there other Scanner
methods that might help with your task?
I strongly encourage you to work with vim for this exercise. In addition to getting familiar with basic editing actions (and remember, this page has stuff about vim), you should also experiment with some of the "advanced" features described in this article.
Similarly, you should get used to working with Java from the command line. Here is a short tutorial on using Java on the Windows command line; if you're using a Mac, watch this short video instead.