I have a sample program which registers people for an airline.
At the Registration class, on the selectSeats method, I have a try catch block, where the catch statement should catch InputMismatchException in case the user inputs a non numeric value.
However, the reinput operation isn't happening, so instead, when an exception happens, the program just throws the error message and proceeds to the end (which leads to unexpected results)
This is the method in question
public void seleccionarAsiento() {
boolean malaSeleccion = true;
do{
try{
System.out.println("\n\n Digite el número de asiento del 0 hasta el 20");
while (malaSeleccion) {
//Selección del hashSet correspondiente a cada vuelo mediante uso de la variable polimorfica "asientos".
if(this.destino.equals("Nicaragua")) {
asientos = asientosNCA;
}
else if (this.destino.equals("Panama") || this.destino.equals("Panamá")) {
asientos = asientosPNA;
}
this.asiento = input.nextInt(); //The part causing the issue
if(this.asiento < 0 || this.asiento > 20) {
System.out.println("\nSelect a seat between 0 and 20.");
} else if (asientos.contains(this.asiento)) {
System.out.println("\nSeat taken, select another one.");
} else if (this.asiento >= 0 && this.asiento <= 20 && asientos.contains(this.asiento) == false) {
asientos.add(this.asiento);
continuarCiclo = false;
malaSeleccion = false;
}
}
} // Fin de bloque try
//Bloque catch para prevenir un input no numerico.
catch (InputMismatchException inputMismatchException) {
System.out.println("Not numeric value, try again.");
input.nextLine();
}
In case this is relevant, since I'm not sure if this could be related to a problem with Inheritance (but I doubt it because the exception is being caught)
This is the start of the class where that method is, and an extension to Exception I added.
public class RegistroCompra {
Scanner input = new Scanner(System.in);
private String destino;
private int asiento;
private boolean continuarCiclo = true;
public static HashSet<Integer> asientosNCA = new HashSet(21);
public static HashSet<Integer> asientosPNA = new HashSet(21);
HashSet<Integer> asientos = null;
class ExcepcionRegistro extends Exception {
ExcepcionRegistro(String s) {
super(s);
}
}
} while (continuarCiclo == true); // Fin de bloque Do
Edit: I solved the issue by making the method recursive in the catch block.
So if it catches the inputmismatchexception (because it was catching it), it cleans the buffer from the invalid input with input.nextLine() and then, the function calls itself again to restart the selection process.
Do it as follows:
public void selectSeat() {
boolean valid = true;
do {
System.out.println("Enter the seat number from 0 to 20");
// ...
try {
this.asient = Integer.parseInt(input.nextLine());
// ...
} catch (InputMismatchException inputMismatchException) {
System.out.println("This is not a numerical value, try again.");
valid = false;
}
} while (!valid);
}
The exception may not the instance of InputMismatchException. You could try add Exception e to take a look the real exception.
catch (InputMismatchException inputMismatchException) {
System.out.println("Este no es un valor númerico, intente de nuevo.");
input.nextLine();
}
catch (Exception e) {
exception.printStackTrace()
input.nextLine();
}
Related
I thought that try and catch blocks stop at the statement the exception is caught, then it proceeds to the catch block. However, this is not the case and it's continuing to run the whole try block.
By the way, this is a tree with reference to 3 nodes: left, middle, and right.
The exception that is being caught is a NullPointerException where the animal name is being repeated twice. For example, 'Python' occurs at the left node, then 'Python' occurs again at the middle node.
Maybe it's because the exception is caught in another class? I'm not too sure.
So, the user input's 'AC' and the exception is caught at the organismTree.addAnimalChild()
else if (command.equalsIgnoreCase("AC")) {
try {
if(organismTree.getCursor().isPlant())
throw new Exceptions.IsPlantException();
if(organismTree.getCursor().isGetAllNodes())
throw new Exceptions.PositionNotAvailableException();
if(organismTree.getCursor().isHerbivore() && !organismTree.getCursor().isCarnivore())
throw new Exceptions.DietMismatchException();
System.out.print("What is the name of the organism?: ");
String addAnimalChild = input.nextLine();
System.out.print("Is the organism a herbivore / a carnivore / an omnivore? (H / C / O) : ");
String addAnimalChildType = input.nextLine();
while (!addAnimalChildType.equalsIgnoreCase("H") && !addAnimalChildType.equalsIgnoreCase("C") && !addAnimalChildType.equalsIgnoreCase("O")) {
System.out.println("Please print out a correct letter");
addAnimalChildType = input.nextLine();
}
if (addAnimalChildType.equalsIgnoreCase("H")) {
organismTree.addAnimalChild(addAnimalChild, true, false);
} else if (addAnimalChildType.equalsIgnoreCase("C"))
organismTree.addAnimalChild(addAnimalChild, false, true);
else
organismTree.addAnimalChild(addAnimalChild, true, true);
System.out.println("A(n) " + addAnimalChild + " has been successfully added as a prey for the " + organismTree.getCursor().getName());
}
catch(Exceptions.IsPlantException | Exceptions.PositionNotAvailableException | Exceptions.DietMismatchException e)
{
e.getMessage();
}
}
addAnimalChild() then redirects to another class.
addAnimalChild method
public void addAnimalChild(String name, boolean isHerbivore, boolean isCarnivore) throws
IllegalArgumentException, Exceptions.PositionNotAvailableException
{
try {
cursor.addPrey(new OrganismNode(name, isHerbivore, isCarnivore));
}
catch(Exceptions.DietMismatchException | Exceptions.IsPlantException e)
{
e.getMessage();
}
}
then it redirects to addPrey() in another class.
addPrey() Method
public void addPrey(OrganismNode preyNode) throws Exceptions.PositionNotAvailableException, Exceptions.IsPlantException, Exceptions.DietMismatchException
{
if (this.isGetAllNodes())
throw new Exceptions.PositionNotAvailableException();
if (this.isPlant()) {
throw new Exceptions.IsPlantException();
}
if(((this.isHerbivore() && !this.isCarnivore()) && preyNode.isCarnivore()) || ((this.isCarnivore() && !this.isHerbivore()) && preyNode.isPlant()) )
throw new Exceptions.DietMismatchException();
if(this.getLeft() == null)
{
this.setLeft(preyNode);
this.getLeft().setLeafNode(true);
if(!preyNode.isCarnivore() && !preyNode.isHerbivore() && !preyNode.isOmnivore())
this.getLeft().setPlant(true);
this.setLeafNode(false);
}
else if(this.getMiddle() == null)
{
try {
this.setMiddle(preyNode);
if (this.getMiddle().getName().equals(this.getLeft().getName())) {
this.setMiddle(null);
throw new IllegalArgumentException();
}
this.getMiddle().setLeafNode(true);
if (!preyNode.isCarnivore() && !preyNode.isHerbivore() && !preyNode.isOmnivore())
this.getMiddle().setPlant(true);
this.setLeafNode(false);
}
catch (IllegalArgumentException e) {
System.out.println("This prey already exists for this predator");
}
}
else if(this.getRight() == null)
{
try {
this.setRight(preyNode);
if (this.getLeft().getName().equals(this.getRight().getName()) || this.getMiddle().getName().equals(this.getRight().getName())) {
this.setRight(null);
throw new IllegalArgumentException();
}
this.getRight().setLeafNode(true);
if (!preyNode.isCarnivore() && !preyNode.isHerbivore() && !preyNode.isOmnivore())
this.getRight().setPlant(true);
this.setLeafNode(false);
}
catch (IllegalArgumentException e) {
System.out.println("Animal already exists");
}
}
}
It continues to print the System.out.println(), even though the exception was indeed caught.
I just thought of something, does the try block continue to run after it finishes the catch block?
It goes through the try block, catches the exception, goes through the catch block, then continues with where the try block left off at?
I can clarify more if you guys need me to.
Sorry if this is really long.
None of your code is catching NullPointerException. You are only catching other Exception classes.
I made a method which purpose is to delete list of questions. The method Test contains questions, answers, number of questions, points. And works fine.
I get the following error:
Unreachable statement on : System.out.println("The test \"" + tests[indice - 1].getNomTest());
Here is the code:
public static int supprimerTest(Test[] tests, int nbrTests) {
int longueurTests = tests.length;
int indice = 0;
int noTest = 1;
int saisieNoTest = 0;
String nomTest;
System.out.println("***DELETE A TEST***\n");
if (nbrTests > 0) {
boolean fin = true;
do{
System.out.print("Please enter a number of the question to be deleted");
try {
indice = Clavier.lireInt();
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
}
}catch (Exception e) {
if (nbrTests < 1){
System.out.print("ERROR ! the number must be between 1 and " + nbrTests + "try again...");
}else {
System.out.println("ERROR ! the number must 1. ... Try again...");
}
}
}while (fin);
}else {
System.out.println("Il n'existe aucun test.");
System.out.print ("\nTPress <ENTRER> to continue ...");
Clavier.lireFinLigne();
}
return nbrTests;
}
Thank you for your help.
The reason you have that error is because exceptions act similar to a return statement where it'll get caught by the nearest Exception handler.
Since you have:
throw new IndexOutOfBoundsException();
Any code underneath that throw will never be reached because it immediately jumps to your catch block.
I hope that makes sense. :)
When you use try statement, it throws exceptions automatically if it is being detected. Therefore, simply take out the throw exception line, then your code should work.
When you throw an exception, the code below the throw will be not executed. Throw invoke exception and the method can continue only in catch/finally block. Lines after throw new IndexOutOfBoundsException(); cannot be reached. Maybe your code should be following:
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
}
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
I'm working on a project where we are to create a cash register system that gives errors for orders of $0.00 and 0 total items. The code for the exceptions is below. I have to use this method.
public boolean ValidateOrderTotal(double total)
{
boolean validTotalFlag = true;
try
{
if (total < 0)
Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
throw invalidTotalEX;
}
catch (Exception invalidTotalEX)(
validTotalFlag = false;
SetTotal(0.00);
System.out.println(invalidTotalEX);
}
return validTotalFlag;
public boolean ValidateOrderProductTotal (double totalItems)
{
boolean validProdctTotalFlag = true;
try
{
if (totalItems < 0)
(Exception invalidProductTotalEX = new Exception ("Product total must be >=0");
throw invalidProductTotalEX;
}
}
catch (Exception invalidProductTotalEX)(
validProdctTotalFlag = false);
SettotalItems (0);
system.out.println (invalidProductTotalEX);
)
return valid ProductTotalFlag
if (total < 0)
Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
throw invalidTotalEX;
needs curly braces
if (total < 0) {
Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
throw invalidTotalEX;
}
You have a second if with the exact same issue.
Also your catch blocks need to use { and } around the statements. You are using ( and ) in some places.
As it throws error when it is 0 it should be:
if (total <= 0) {
Exception invalidTotalEX = new Exception ("Total mst be > $0.00");
throw invalidTotalEX;
}
"catch (Exception invalidTotalEX)(" -
there should be last '{' after "catch (Exception invalidTotalEX)(" instead of '('
Variable name does not matter, for example:
viktor#Viks-pro:~/tmp/test $ cat ExTest.java
import java.util.*;
public class ExTest
{ public static void main(String[] args)
{ try
{ throw new Exception("Something should be different");
}
catch(Exception e)
{ System.out.println("Exception: "+e.getMessage());
}
}
}viktor#Viks-pro:~/tmp/test $ java ExTest
Exception: Something should be different
I'm having a problem with 2 variables, the first of them is called "Num_Viajes" and the function is increasing it value by one everytime I call the method "de_Viaje". The second is called "Total_Pasajeros" and the function is make an addition between itself and another variable called "Num_Pasajeros", both variables are int.
Anyway the thing is, when I call the Method "Reporte_Final" both variable should print their results, for example: If I call the Method "de_Viaje" 2 times and I enter the value "45" for the variable "Num_Pasajeros" the program should return this:
Num_Viajes = 2
Total_Pasajeros = 90
But instead, it returns:
Num_Viajes = 1
Total_Pasajeros = 45
So I think that's because the program is not saving the values of my variables, so they are always restarting. How can I fix this?
Here's the code:
import javax.swing.*;
public class Empresa_Autobuses
{
String Tipo_Vehiculo;
String Analisis_Viaje;
int Num_Pasajeros;
int Num_Viajes;
int Total_Pasajeros;
int Prom_Pasajeros;
public static void main(String ... args)
{
boolean Bandera_Falsa = true;
Empresa_Autobuses Viajero = new Empresa_Autobuses();
do
{
Viajero.de_Viaje();
Viajero.Reporte_Viaje();
Viajero.Solicitud_Viaje();
Viajero.Reporte_Final();
}while(Bandera_Falsa == true);
}
public void de_Viaje()
{
Empresa_Autobuses Viajero = new Empresa_Autobuses();
Tipo_Vehiculo = JOptionPane.showInputDialog("Selecciona el Tipo de Autobus (G = Grande, P = Pequeño").toUpperCase();
Num_Pasajeros = Integer.parseInt(JOptionPane.showInputDialog("Introduzca el Número de Pasajeros: "));
if(Tipo_Vehiculo.equals ("G"))
{
if(Num_Pasajeros > 60)
{
JOptionPane.showMessageDialog(null, "¡Se ha superado la Capacidad Máxima del Autobus!");
Viajero.Solicitud_Viaje();
}
else if(Num_Pasajeros >= 30)
{
Analisis_Viaje = "Ganancia";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
else
{
Analisis_Viaje = "Pérdida";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
}
else if(Tipo_Vehiculo.equals ("P"))
{
if(Num_Pasajeros > 20)
{
JOptionPane.showMessageDialog(null, "¡Se ha superado la Capacidad Máxima del Autobus!");
Viajero.Solicitud_Viaje();
}
else if(Num_Pasajeros >= 10)
{
Analisis_Viaje = "Ganancia";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
else
{
Analisis_Viaje = "Pérdida";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
}
else
{
JOptionPane.showMessageDialog(null, "Opción Incorrecta");
Viajero.Solicitud_Viaje();
}
}
public void Reporte_Viaje()
{
JOptionPane.showMessageDialog(null, "Reporte de Viaje\nEl Tipo de Autobus fue: "+Tipo_Vehiculo+"\nEl Total de Pasajeros en el Viaje fue de: "+Num_Pasajeros+"\n"+Analisis_Viaje);
}
public void Solicitud_Viaje()
{
Empresa_Autobuses Viajero = new Empresa_Autobuses();
String Solicitud;
boolean flag = true;
do
{
Solicitud = JOptionPane.showInputDialog("¿Quiere realizar otro Viaje? (Y/N)").toUpperCase();
if(Solicitud.equals ("Y"))
{
Viajero.main();
}
else if(Solicitud.equals ("N"))
{
flag = true;
}
else
{
JOptionPane.showMessageDialog(null, "Opción Incorrecta");
flag = false;
}
}while(flag == false);
}
public void Reporte_Final()
{
Prom_Pasajeros = Total_Pasajeros / Num_Viajes;
JOptionPane.showMessageDialog(null, "El Número de Viajes realizados fue de: "+Num_Viajes+"\nEl Total de Pasajeros fue de: "+Total_Pasajeros+"\nEl Promedio de Pasajeros fue de: "+Prom_Pasajeros);
System.exit(9999);
}
}
The problem does not seem to be where you think it is. What happens when Num_Pasajeros>60? Why is the increment within a "then" block if it should always happen?
Edit
It appears very likely that the problem is that you run your main procedure from within your program. This second invocation creates a whole new object that is not related to the one you've been working with! Don't do that, and you should probably be fine. You have some issues with your Swing threading, but you probably shouldn't think about that yet.
Should debug it, take a break point # Empresa_Autobuses Viajero = new Empresa_Autobuses(); and see whats happening what case (if/else branch) is running/executing, what are your variable actual values...
Anyway if you observe it carefully: if the care type is P, then you total_pasajeros will not summed with num pasarejos.
Tipo_Vehiculo.equals ("P"))
And +1 for the Java Code Convention: http://web.archive.org/web/20140222045352/http://www.oracle.com/technetwork/java/codeconv-138413.html
(You make everybody job easier here if you keep youeself to that)
p.s: I do not know Italian language but common sense suggest these....
I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));