Keyboard Input and Type Conversion

Java programs are generally written to interact with other programs running on web servers or sometimes via a graphical user interface. Keyboard and console based programs are more rare, but it is possible to write programs this way, albeit in a slightly more complicated fashion than equivalent programs in other languages. Before we start though, it is useful to understand what a library is.

Library code

Most programs are very similar in what they are trying to achieve. As the saying goes, “there’s no point in reinventing the wheel”, so programmers tend to make use of code that has already been written and tested by someone else rather than write their own code that does exactly the same thing. This code is usually packaged up into what is known as a library and is therefore called library code. All the programmer has to do to use this prewritten code is to tell their compiler where it is, and then the programmer is reponsible for making use of the library code as they need in their own program.

Libraries are usually packaged up with other libraries according to what services they provide. For example there might be a library package for maths functions, another one for networking, and another for producing sound or music. In Java, the libraries can be included by using the import statement, before the class definition:

import java.math; // the standard Java math library
import java.sql; // the standard Java SQL database library

// for libraries that are not standard Java libraries, the
// code has to be downloaded and your compiler needs to be
// told where the files are stored, in the IDE

import org.jaudiotagger.audio.AudioFile // external library

public class BuildSongLibrary{

...

How do you know what’s inside a library and how to use the code? Usually there is a document available as a web page that tells you exactly what methods are available, and how to call them. For the standard Java classes they come as part of the Java SDK. In BlueJ they can easily be accessed by going to the Help>Java Class Libraries menu item, or you can visit them on the Oracle website. Note that package has a specific meaning in Java, and the documentation is organised around packages. Choose the package from the top left of the screen, then the class from the bottom left, then you can scroll through the main display in the centre of the screen to find the methods available.

Activity 1

  • Try to find the Scanner class within the java.util documentation
  • What methods does Scanner have?

Using the Scanner class

The skeleton program below shows you how to import the Scanner class but doesn’t make use of it yet. To do so, you will need to create an object from the Scanner class inside main, and then make use of that object to use the methods available.

import java.util.Scanner; // import the Scanner class

public class myTestProgram{

  public static void main(String[] args){

  }

}

In Java, the keyword new is used to create a new object from a class. We need to create an object from the Scanner class and use the object’s methods to get data from the keyboard. The following lines do exactly that:

// Scanner is the class used as the template for our object
Scanner keyboard = new Scanner(System.in); 

String s; // declare a string variable to hold the input

// use the next() method to get the input from the keyboard
s = keyboard.next(); // keyboard is the object
 

Activity 2

Do the following:

  1. Integrate the two code examples above to create a program that takes input from the keyboard, and stores it in a string.
  2. Add code before the part that reads the keyboard that prints a message asking the user to type in their name.
  3. Add code that prints out “Hello ” followed by the contents of the string.

next() returns data as a String. Scanner has other methods that return floats (nextFloat), ints (nextInt) etc. Java also provides code that will allow us to convert from the String datatype to numeric datatypes so that we can then perform calculations. For example,

/* a string that contains something that looks like a number can be converted into an integer using the Integer class, with the syntax below */

int myInt = Integer.parseInt(string1); 

// if string1 contained "23", myInt will now contain 23.

Casting

// are these code fragments illegal?!

char myChar='A';
int myInt=(int)myChar; 

int myOtherInt=66;
char myOtherChar=(char)myOtherInt;

If you were to type in the code above it would compile without any errors. This seems suprising given that we previously said that Java was fussy about types.

What has happened is that the compiler is being told to temporarily assume that one datatype is actually another. It only works for certain related datatypes. For example if a variable contains an integer it can be cast into a char because chars have a numeric value (the ASCII or Unicode value).

In the example, myInt will contain 65, because the ASCII value of the letter capital A, is 65. The variable myOtherChar will contain the letter B, because 66 in the ASCII table is B.

This process of temporarily treating one data type as another is called casting. The brackets and datatype in front of the variable is what is doing the cast, e.g. (int)myChar is casting the variable myChar into an int.

Try casting for yourself. What do you think a float could be cast into?

Activity 3

Now try the following:

  1. Write a program that takes two integers from the keyboard, separated by spaces
  2. Add the two numbers together and print the result
  3. Modify it to work with two floats instead
  4. Make sure you have commented every line and understand it
  5. Change your temperature conversion program from a previous lesson to take input from the keyboard and convert to or from centigrade or fahrenheit.

Knowledge check

  • What is Scanner, a class or an object?
  • What methods are there in a Scanner that we can use to get input from the keyboard?
  • Why might you need to convert datatypes?
  • What is the difference between converting and casting?