赶上除以零的问题

时间:2018-11-22 04:48:43

标签: java

教授要求我们制造一个可以进行基本计算的字符计算器。差不多完成了,但是我有一个问题要解决被零除的问题。每个人都知道一个数字不能除以零。如果我问用户两个浮点数,而他给我的第二个浮点数是0,该怎么办?我知道它应该在division()下,并且我已经尝试了很多次使用if语句,但无法正常工作。如果用户做错了,我该写些什么让用户有第二次机会重写两个浮点数,并告诉他第二个数字不应为零。如果用户首先输入错误,那么我编写的程序只会给出错误的答案。有人可以帮我吗?

import java.util.Scanner;

public class Calculator {

    static Scanner scan;

    public static void main(String[] args) {

        String choice = "";
        scan = new Scanner(System.in);

        while(true) {

            System.out.println("Welcome to <'s> Handy Calculator\n"+"\n\t1. Addition\n\t2. Subtraction\n\t3. Multiplication\n\t4. Division\n\t5. Exit\n");
            System.out.println("What would you like to do? ");

            choice=scan.nextLine();

            if (choice.equals("1")) {

                if(!addition()){
                    System.out.println("\nYou have entered invalid input. Please try again");
                }
                    System.out.println("\nPress enter key to continue...");
                    scan.nextLine();
            }

            else if(choice.equals("2")){

                if(!subtraction()){
                    System.out.println("\nYou have entered invalid input. Please try again");
                }
                    System.out.println("\nPress enter key to continue...");
                    scan.nextLine();
            }

            else if(choice.equals("3")){

                if(!multiplication()){
                    System.out.println("\nYou have entered invalid input. Please try again");
                }
                    System.out.println("\nPress enter key to continue...");
                    scan.nextLine();
            }

            else if(choice.equals("4")){

                if(!division()){
                    System.out.println("\nYou have entered invalid input. Please try again");
                }
                    System.out.println("\nPress enter key to continue...");
                    scan.nextLine();
            }

            else if(choice.equals("5")){

                System.out.println("\nThank you for using <'s> Handy Calculator");
                break;

            }

            else{

                System.out.println("\nInvalid input. Please input an integer between 1 and 5\n");
                continue;

            }

        }

    }

    private static boolean addition() {

        System.out.println("\nPlease enter two floats to add, separated by a space: ");

        String input = scan.nextLine();

        try{
            Float f1 = Float.parseFloat(input.split(" ")[0]);
            Float f2 = Float.parseFloat(input.split(" ")[1]);
            System.out.println("\nResult of adding "+f1+" and "+f2+" is: "+(f1+f2));
        }
        catch(Exception e){

            return false;

        }

        return true;    
    }

    private static boolean subtraction() {

        System.out.println("\nPlease enter two floats to subtract, separated by a space: ");

        String input = scan.nextLine();

        try{
            Float f1 = Float.parseFloat(input.split(" ")[0]);
            Float f2 = Float.parseFloat(input.split(" ")[1]);

            System.out.println("\nResult of subtract "+f2+" from "+f1+" is: "+(f1-f2));
        }
        catch(Exception e){

            return false;

        }

        return true;
    }       

    private static boolean multiplication() {

        System.out.println("\nPlease enter two floats to multiply, separated by a space: ");

        String input = scan.nextLine();

        try{

            Float f1 = Float.parseFloat(input.split(" ")[0]);
            Float f2 = Float.parseFloat(input.split(" ")[1]);

            System.out.println("\nResult of multiply "+f1+" and "+f2+" is: "+(f1*f2));

        }
        catch(Exception e){

            return false;

        }

        return true;

    }

    private static boolean division() {

        System.out.println("\nPlease enter two floats to divide, separated by a space: ");

        String input = scan.nextLine();

        try{

            Float f1 = Float.parseFloat(input.split(" ")[0]);
            Float f2 = Float.parseFloat(input.split(" ")[1]);
            if(f2==0) {
                System.out.println("the second number should not be zero, please do agian");
                scan.nextLine();
            }
            System.out.println("\nResult of dividing "+f1+" by "+f2+" is: "+(f1/f2));
        }

        catch(Exception e){

            return false;

        }

        return true;

    }

}

2 个答案:

答案 0 :(得分:0)

  

我该写些什么让用户有第二次重写两次的机会   如果他做错了,就会浮动,并告诉他第二个数字不应该   为零?如果用户将我编写的程序给出错误的答案,   首先输入错误。

您需要一个while循环。我已经测试过了,这可以解决问题:

private static boolean division() {

    System.out.println("\nPlease enter two floats to divide, separated by a space: ");

    String input = scan.nextLine();
    Float f1 = 0.0f;
    Float f2 = 0.0f;

    boolean validInput = false;
    while (!validInput) {
        f1 = Float.parseFloat(input.split(" ")[0]);
        f2 = Float.parseFloat(input.split(" ")[1]);
        if (f2 == 0) {
            System.out.println("the second number should not be zero, please do agian");
            input = scan.nextLine();
        } else {
            validInput = true;
        }
    }
    System.out.println("\nResult of dividing " + f1 + " by " + f2 + " is: " + (f1 / f2));

    return true;
}

并且您不需要try/catch-代码永远不会从头开始抛出异常。

答案 1 :(得分:0)

您必须在循环中检查输入float是否等于0,如果输入等于System.out.println("\nPlease enter two floats to divide, separated by a space:"); float f1 = scan.nextFloat(); float f2 = scan.nextFloat(); while (Float.compare(f2, 0) == 0) { System.out.println("the second number should not be zero, please do agian"); f2 = scan.nextFloat(); } return String.format(LOCALE, "\n%.2f / %.2f = %.2f", f1, f2, f1 / f2); ,请取消输入。

public final class Calculator {

    private static final String TITLE = "<'s> Handy Calculator";
    private static final Locale LOCALE = Locale.US;

    private static final char EXIT = '0';

    private static void proceed(Scanner scan) {
        while (true) {
            try {
                System.out.println("Welcome to " + TITLE + '\n');
                Stream.of(Operation.values())
                      .filter(op -> Objects.nonNull(op.title))
                      .forEach(op -> System.out.format("\t%s. %s\n", op.id, op.title));
                System.out.println("\t" + EXIT + ". Exit\n");
                System.out.println("What would you like to do? ");

                char choice = scan.next().charAt(0);

                if (choice == EXIT) {
                    System.out.println("\nThank you for using " + TITLE);
                    return;
                }

                System.out.println(Operation.parseId(choice).apply(scan));
                System.out.println();
            } catch(Exception e) {
                System.err.println("\nYou have entered invalid input. Please try again");
            } finally {
                System.out.println("\nPress enter key to continue...");
                scan.nextLine();
            }
        }
    }

    private enum Operation implements Function<Scanner, String> {
        UNKNOWN('\0', null) {
            @Override
            public String apply(Scanner scan) {
                return "\nInvalid input. Please input an integer between 1 and 5";
            }
        },
        ADDITION('1', "Addition") {
            @Override
            public String apply(Scanner scan) {
                System.out.println("\nPlease enter two floats to add, separated by a space:");
                float f1 = scan.nextFloat();
                float f2 = scan.nextFloat();
                return String.format(LOCALE, "\n%.2f + %.2f = %.2f", f1, f2, f1 + f2);
            }
        },
        SUBTRACTION('2', "Subtraction") {
            @Override
            public String apply(Scanner scan) {
                System.out.println("\nPlease enter two floats to subtract, separated by a space:");
                float f1 = scan.nextFloat();
                float f2 = scan.nextFloat();
                return String.format(LOCALE, "\n%.2f - %.2f = %.2f", f1, f2, f1 - f2);
            }
        },
        MULTIPLICATION('3', "Multiplication") {
            @Override
            public String apply(Scanner scan) {
                System.out.println("\nPlease enter two floats to multiply, separated by a space:");
                float f1 = scan.nextFloat();
                float f2 = scan.nextFloat();
                return String.format(LOCALE, "\n%.2f * %.2f = %.2f", f1, f2, f1 * f2);
            }
        },
        DIVISION('4', "Division") {
            @Override
            public String apply(Scanner scan) {
                System.out.println("\nPlease enter two floats to divide, separated by a space:");
                float f1 = scan.nextFloat();
                float f2 = scan.nextFloat();

                while (Float.compare(f2, 0) == 0) {
                    System.out.println("the second number should not be zero, please do agian");
                    f2 = scan.nextFloat();
                }

                return String.format(LOCALE, "\n%.2f / %.2f = %.2f", f1, f2, f1 / f2);
            }
        };

        private final char id;
        private final String title;

        Operation(char id, String title) {
            this.id = id;
            this.title = title;
        }

        public static Operation parseId(char id) {
            for (Operation operation : values())
                if (id == operation.id)
                    return operation;
            return UNKNOWN;
        }
    }

    public static void main(String... args) {
        try (Scanner scan = new Scanner(System.in)) {
            scan.useLocale(LOCALE);
            proceed(scan);
        }
    }

}

下面,我对您的代码进行了重构。希望您能更清楚地了解它。

from typing import List
def find_smallest(arr:List) -> int:
    smallest = arr[0] #set pivot
    smallest_index = 0
    for i in range(1, len(arr)):
        if arr[i] < smallest:
            smallest = arr[i]
            smallest_index = i
    return smallest_index

def selection_sort(arr) -> List:
    new_arr = []
    for i in range(len(arr)):
        smallest = find_smallest(arr)
        new_arr.append(arr.pop(smallest))
    return new_arr