Input and Output
14. Converting to Integers
Answer:
No. The program only works with strings of digits that can be converted into integer data.
Converting to Integers
Converting to Integers
Here is a statement from the program:
num = scan.nextInt();
Assignment statements work in two steps:
- Evaluate the expression on the right of the equal sign,
- Put the value into 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 them into an int
, if that is possible. 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? Click to see if you are correct.
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