In this step, we will test our SquareRootChecker.java
program with negative numbers and consider what happens if the user enters something that is not an integer.
In the code we wrote, we included a check for negative numbers:
if (number < 0) {
System.out.println("Cannot calculate the square root of a negative number.");
}
This if
statement handles the case where the user enters a negative integer. Let's test this part of the code.
-
Make sure you are in the ~/project
directory in the Terminal.
-
Run the compiled program:
java SquareRootChecker
-
When prompted, enter a negative number, for example, -4
, and press Enter.
Enter an integer: -4
Cannot calculate the square root of a negative number.
As expected, the program correctly identifies that it cannot calculate the square root of a negative number and prints the appropriate message.
Now, let's consider what happens if the user enters input that is not an integer, such as text or a decimal number. Our program uses scanner.nextInt()
to read the input. This method is designed to read only integer values. If the user enters something that cannot be parsed as an integer, a InputMismatchException
will occur, and the program will crash.
Handling such errors gracefully is an important part of writing robust programs. For this introductory lab, we won't implement full error handling for non-integer input, but it's important to be aware that this can happen. In future labs, you will learn techniques like try-catch
blocks to handle exceptions and make your programs more resilient to unexpected user input.
For now, let's just observe what happens when you enter non-integer input.
-
Run the compiled program again:
java SquareRootChecker
-
When prompted, enter some text, for example, hello
, and press Enter.
Enter an integer: hello
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at SquareRootChecker.main(SquareRootChecker.java:9)
You will see an error message indicating an InputMismatchException
. This is because scanner.nextInt()
expected an integer but received "hello".
This step highlights the importance of considering different types of user input and how your program will handle them. While our current program is simple, understanding these potential issues is crucial for developing more complex applications.