Java Trouble с исключениями.Одно исключение не позволяет мне исправить свои данные, а другое - - PullRequest
0 голосов
/ 12 апреля 2019

У меня есть мой код, который позволяет пользователю вводить сумму дохода.Мое специальное исключение (негативное исключение) позволяет мне ввести доход после того, как оно сообщит мне, что никакие отрицательные исключения не допускаются.Я использовал тот же код с несколькими изменениями для обработки исключения InputMismatchException.Дело в том, что когда я вхожу в InputMismatchException, он пропускает часть, в которую я попадаю, чтобы повторно ввести свой ввод.Он пропускает вперед к оператору finally и печатает System.out.println (txp).Я только публикую код, который, по моему мнению, имеет отношение к проблеме, если вам нужно больше информации, дайте мне знать, пожалуйста.

На самом деле все, что я пробовал, - это перемещать вещи в разных областях.В большинстве случаев это просто сбой программы.

Main:

public class callTaxCode_Test {

    static float income;
    public static void main(String[] args) throws negativeException{//, InputMismatchException{

        //GUI will consist of: one text field for income
        //                     drop down box with each type (6 total)
        //                     enter button, tax cash button

        Scanner kb = new Scanner(System.in);
        System.out.println("Enter Type");

        String input = kb.nextLine();
        System.out.println("Income: "); 

        if(input.equalsIgnoreCase("corp")) {

            try {
                income = kb.nextFloat();
                corporation c = new corporation(input, income);
            }
            catch(InputMismatchException e) {
                System.out.println("Invalid Input!");
                System.out.println("Please Enter the correct income: ");
                income = kb.nextFloat();
                //corporation c = new corporation(input, income);
            }
            catch(negativeException e) {

                System.out.println(e.getMessage());
                System.out.println("Please Enter the correct income: ");
                income = kb.nextFloat();
                corporation c = new corporation(input, income);
            }
            finally {
                corporation c = new corporation(input, income);
                taxpayerInfo<Float> txp = new taxpayerInfo<Float>(taxpayer.getIncome(),
                                                                  taxpayer.getFlatRate(), 
                                                                  taxpayer.getTaxRate(), 
                                                                  taxpayer.getIncome());

        txp.setType(input);
        txp.calcTax();
        System.out.println(txp);
        }
    }

Корпоративный класс:

public class corporation extends taxpayer{

    //for corporations taxable income is 100% of income

    //there is no flat rate so we will set that to 0

    //tax rate is 21%


    //tax = .21 \* income


    public corporation(String type, float income) throws negativeException{



        setType(type);

        setIncome(income);

        flatRate = 0;

        taxRate = .21F;

        taxableIncome = income;

    }

}

налогоплательщик (который служит моим суперклассом):

public class taxpayer{

    //corp, trust, person can all follow the same formula

    //tax = flat rate + (tax rate \* taxable income)



    //corp's flat rate is 0, and its taxable income is 100% of income

    //also has a set tax rate of 21%

    //tax = 0 + (.21 \* income)



    //trust + person taxable income is determined by the excess amount of income

    //after the brackets minimum income allowing them into the bracket

    [//e.g](//e.g). It takes 38,700 to belong in the 3rd bracket of a single filer

    //taxable income = income - 38700

    //everything else in these classes are determined by the bracket their income places them

    protected static String type;

    protected static float income;

    protected static float flatRate;

    protected static float taxRate;

    protected static float taxableIncome;





    //get income

    public static float getIncome() {



        return income;

    }

    //set income, throw exception if negative

    public static void setIncome(float income) throws negativeException{

        if(income < 0) {

            throw new negativeException();

        }

        else {

            taxpayer.income = income;

        }

    }

    //set type

    public static void setType(String type) throws InputMismatchException{


        taxpayer.type = type;

    }

Отрицательное исключение Класс:

public class negativeException extends Exception {

    public negativeException() {
            super("Negative Values are not allowed!");

        }
    }

Я ожидаю, что мое InputMismatchException будет вести себя как мое absoluteException.То есть, когда он ловит исключение, это позволяет мне вводить новый доход, что позволяет мне делать с помощью currentException.Тем не менее, он пропускает, позволяя мне повторно ввести доход, и переходит к окончательному утверждению.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...