简体   繁体   中英

Try / catch in a do-while loop to check user input (array) - wrong boolean initialization and position

I am a Java beginner and I am learning to manage Exceptions and 2D arrays. I am doing an exercise to plot in a 2D array the result of the sales of different car models.

I have mixed the way to deal with Exception by using a try catch or by throwing a custom Exception. On a custom Exception I have an issue I am not able to solve.

In the Seller class:

  • In line 16, IDE tells me that the variable "correct" initializer to false is redundant冗余初始化
  • In line 26, IDE tells me that the while condition is always false. do while 循环的最终条件错误

I wanted to declare the boolean correct inside the inner loop to check for each value if the input was correct (an integer) or not and then to change the value to true at the end of the try in case the parseInt was successful. By reading the comments from the IDE I understand that the boolean correct is never changed to true even if I select an integer but I do not understand why.

import java.util.Scanner;
public class Sellers {
    public static void main(String[] args) throws NumberArrayException {
        Scanner myObj = new Scanner(System.in);

        int nbrOfSellers = CheckInput.control("Enter the number of sellers = ");
        int nbrOfModels = CheckInput.control("Enter the number of models = ");
        int[][] sales = new int[nbrOfSellers][nbrOfModels];

        String[] nameOfSellers = Characters.construction("seller", nbrOfSellers);
        String[] nameOfModels = Characters.construction("model", nbrOfSellers);


        for(int i = 0; i < nbrOfSellers; i++) {
            for(int j = 0; j < nbrOfModels; j++) {
                boolean correct = false;
                System.out.print("Enter the sales for the seller " + nameOfSellers[i] + " for the model " + nameOfModels[i] + " = ");
                do {
                    try {
                        String input = myObj.nextLine();
                        sales[i][j] = Integer.parseInt(input);
                        correct = true;
                    } catch (NumberFormatException e) {
                        throw new NumberArrayException();
                    }
                }while (!correct) ;
            }
        }
        for(int i = 0; i < nbrOfSellers; i++) {
            for(int j = 0; j < nbrOfModels; j++) {
                System.out.print(sales[i][j] + " ");
            }
            System.out.println();
        }
    }
}

import java.util.Scanner;
public class Characters {
    public static String[] construction(String character, int maxSize) {
        Scanner myObj = new Scanner(System.in);
        String[] myArray = new String[maxSize];
        for(int i = 0; i < maxSize; i++) {
            System.out.print("Enter the name of the " + character + " ");
            myArray[i] = myObj.nextLine();
        }
        return myArray;
    }
}

import java.util.Scanner;
public class CheckInput {
    public static int control(String message) {
        boolean correct = false;
        int number = -1;
        Scanner myObj = new Scanner(System.in);
        do {
            try {
                System.out.print(message);
                String input = myObj.nextLine();
                number = Integer.parseInt(input);
                correct = true;
            } catch(NumberFormatException e) {
                System.out.println("Enter a number");
            }
        }while(!correct);

        return number;
    }
}

public class NumberArrayException extends RuntimeException {
    public NumberArrayException() {
        super();
    }
}

There are two ways that this do-while-loop can exit: correct is true or an exception is thrown.

Technically, an exception can only be thrown in the two lines above the statement correct = true . Since you are throwing the NumberArrayException inside the loop, it will either exit because of it, or correct will be set true .

When we reach while (!correct) , then correct is always true since it got set. Otherwise we would have exited with an exception. Therefore, this loop never has a second iteration.

To fix it, you can just avoid throwing an exception when the provided input cannot be parsed. The loop will then let the user enter another integer.

do {
    try {
        String input = myObj.nextLine();
        sales[i][j] = Integer.parseInt(input);
        correct = true;
    } catch (NumberFormatException e) {
        // output error message for the user here
    }
} while (!correct);

Your code is pretty good and well structured. Actually, you should compare the source of CheckInput.control to see why it does not have the mentioned warnings: you initialize the local variable correct as it should be and no exception is thrown in case of invalid input, thus letting the user to correct it. If you throw an exception from inside do-while loop as in the main method, then the false value of correct is never used.

You should resolve these warnings by reusing existing CheckInput.control when initializing the 2D sales array. Also there's a typo when creating nameOfModels -- nbrOfModels should be passed as an argument.

String[] nameOfSellers = Characters.construction("seller", nbrOfSellers);
String[] nameOfModels = Characters.construction("model", nbrOfModels);


for(int i = 0; i < nbrOfSellers; i++) {
    for(int j = 0; j < nbrOfModels; j++) {
        sales[i][j] = CheckInput.control("Enter the sales for the seller " + nameOfSellers[i] + " for the model " + nameOfModels[i] + " = ");
    }
}

When you throw an exception it exits the function and throws the exception. So instead of throwing the exception in the catch block just print and error message. So that user can understand the error and enter input again.

 do {
     try {
          String input = myObj.nextLine();
          sales[i][j] = Integer.parseInt(input);
          correct = true;
          } catch (NumberFormatException e) {
                System.out.println("Wrong input format. Please enter a number");
          }
 }while (!correct) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM