In the last lesson, we created a multiplication program that asks for the user to input 2
int values and then returns the product. In this lesson, we are going to go over the different methods associated with the
Scanner class. This will help illustrate how imported classes have a variety of different methods to deal with different variable types.
If possible, pull up your code from Lesson 17. In its current state, we know that it will not work with doubles. If we try to put in the double value 12.0 , we get a
Looking at our code, we know that our issue is arising from using the
nextInt() method for a double value. So, to fix our code, we are going to find a list of
Scanner methods to help figure out what the method name is for working with doubles.
Although it is important to memorize as many of the common methods as possible to be more proficient, it is equally important to be able to know how and where to find information when you need it. Most programmers are proficient with multiple languages, but still rely on outside sources to help in their coding.
Fortunately, there are a plethora of resources for Java. I have found that one of the best resources for Java is straight from the horse’s mouth – Oracle. Oracle, the owner of Java, has just about all the information you need concerning the Java language. It is easy to find what you need by typing what topic you are interested in Java and going to the Oracle website.
For example, when I search in “Java Scanner class methods,” my 2nd result is from the Oracle website: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html. Although the content is a little dry, you can scroll down the page and find a “Method Summary” block that lists all the methods associated with the Scanner class.
On the Oracle page, we find that if we want double values to work with our Scanner, we will have to use the method
nextDouble(), instead of
nextInt(). Although you could have probably guessed this method on your own, the more complex our topics become, the more important it is to be able to quickly find reliable resources to help your coding process.
Now that we know the double Scanner method, we can go to our code from last lesson and swap out
nextDouble(). Also, we can change the
double values, instead of
int. After making those changes, your code should look like the following:
With these changes, we can now use our
Scanner to read and store double values!
I know this lesson did not cover much coding, as much as finding information. However, it is important to know how and where to quickly find information for Java. Even the best coders forget method names at times and find themselves searching Google for the answers. Just know that this is a large part of the coding process, especially in the beginning. See you next in the next lesson!