top of page

Week 8

In Week 8 we will see more on the Scanner / PrintStream class and how to use it. We will also learn about GUIs.

Scanner

Tokens

24  2.92  "John Smith"

We have seen that a given sequence of symbols can be decomposed into tokens. When a file is read by a scanner, the input is split into tokens and each token is processed individually. Each token can be interpreted as one of multiple types, e.g. an int could also be a long, float or double. Whenever one of the tokens is processed and we move to the next token in the sequence we say that the token was consumed. The underlying data is not affected by the scanner consuming tokens.

Scanner

Exceptions

NoSuchElementException.png
InputMismatchexception.png

Whenever we use a Scanner object we must be careful not to incorrectly consume the given tokens in the input. We cannot consume a token of type String as an int and we can also not consume a token if all tokens in the sequence have already been consumed. The following two types of exception can occur

  • NoSuchElementException: All tokens in the sequence have been consumed and you attempted to consume a token.

  • InputMismatchException: There are still tokens to be consumed but you attempted to consume the next token as a non-compatible type, e.g. the next token is a String and you attempted to consume a double type value.

To avoid exceptions you should make use of the hasNextType() methods given by the Scanner class. This allows you to first verify that the token you want to consume exists.

Scanner

Declaring Exceptions

CatchingExceptions.png

When we work with a Scanner to read a file we may run into the problem that the specified file does not exist yet. This will cause an error which Java does not know how to handle. This is because not finding a file should not directly cause the program to stop its execution as the user could specify to simply move on or look for a different file. We could even want to first check if a file exist and then if it does not exists create the file. This is the reason why the default behaviour of Java is not to directly abort. We must however tell Java what we want to happen. In many cases we add the "throws Exception" method signature to the methods which were affected if a file was to be not found. This tells Java that it should stop execution an display an error message.

GUI

Definition

GUI stands for Graphic User Interface and allows for more detailed output like images, graphics and even interactive windows. The console has its limitations and thus we choose to introduce a more powerful medium for output. Reading the corresponding quickguide is a good way to recapitulate the gui library.

bottom of page