Converting to Integers

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

No. The program only works with strings of digits that can be converted into integer data.

Converting to Integers

Here is a statement from the program:

num = scan.nextInt();

Assignment statements work in two steps:

  1. Evaluate the expression on the right of the equal sign,
  2. Put the value in the variable on the left.

In this particular assignment statement, the expression on the right scans a group of characters from the input stream and converts then into an int, if they are correct. Then the numeric result is stored into num.

If the group of characters cannot be converted, Java throws an Exception and stops your program. An Exception object contains information about what went wrong in a program. Industrial-strength programs may examine the exception and try to fix the problem. Our programs (for now) will just stop.

QUESTION 14:

Which of the following inputs would be correct input for the program?

Enter an integer:  1492
Enter an integer:  Fourteen ninety two
Enter an integer:  14.92
Enter an integer:  -1492
Enter an integer:  1 4 9 2