I would like the code to catch the error when the user enters a string instead of an integer. You can see I have tried a try catch block which is still not working. Everything else is perfect apart from that. How can I solve this?
Here is how the output should be:
Welcome to the Squares and Cubes table
Enter an integer: five
Error! Invalid integer. Try again.
Enter an integer: -5
Error! Number must be greater than 0
Enter an integer: 101
Error! Number must be less than or equal to 100
Enter an integer: 9
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
Continue? (y/n): y
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
Here is the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class cube2 {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
try {
break;
}
catch (NumberFormatException e) {
System.out.println("Error! Invalid integer. Try again.");
}
System.out.print("Enter an integer: ");
integer = sc.nextInt();
if(integer<0){
System.out.println("Error! Number must be greater than 0");
System.out.print("Enter an integer: ");
integer = sc.nextInt();
}
if(integer>100){
System.out.println("Error! Number must be less than or equal to 100");
System.out.print("Enter an integer: ");
integer = sc.nextInt();
}
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
tryblock - why do you use it then?tryis used to run exception sensitive code and catch the exception if it arises ... your sensitive code is outside of thattryblock and you only run the commandbreakin there, which won't fail/throw an exception. Oracle provides tutorials, you should follow them: docs.oracle.com/javase/tutorial/essential/exceptions/…