简体   繁体   English

实施try and catch块

[英]Implementing a try and catch block

I am finally (almost) done with a little calculator project that I have been working on. 我终于(几乎)完成了一个我一直在从事的小计算器项目。 Currently, it works with addition, subtraction, multiplication, division, mod, squaring, and negation of doubles and responds to some strings such as "exit", "clear", and "help". 当前,它可以与加,减,乘,除,mod,平方和双精度取反一起工作,并对某些字符串(例如“ exit”,“ clear”和“ help”)作出响应。

I just need help implementing a try and catch block to return a message in the console such as "Invalid Input" whenever the user enters anything that is not a number after the console says "Enter first number" or "Enter second number". 只要用户在控制台说“输入第一个数字”或“输入第二个数字”之后输入任何非数字的内容,我只需要实现一个try and catch块来在控制台中返回一条消息,例如“ Invalid Input”。

I have messed around with a few different methods but nothing seems to be working. 我已经弄乱了几种不同的方法,但似乎没有任何效果。 Advice would be greatly appreciated. 建议将不胜感激。 Code: 码:

import java.util.Scanner;


public class exit {

    static double num1;
    static double num2;
    static String operation;

    public static void main(String[] args) {

        boolean run = true;

        while (run) {

            System.out.println(" Enter: \n \b help for all usable operations \n continue to use the    calculator");
            Scanner input = new Scanner(System.in);
            String str1 = input.next();

            if (str1.equals("exit")) {

                System.exit(0);
            } else if (str1.equals("clear")) {

                System.out.println("0.0");
            } else if (str1.equals("help")) {
                System.out.println("please enter:\n + for addition \n - for subtraction \n * for     multiplication \n / for division \n -x for negation \n x^2 for squaring\n % for mod \n  remember to only input integer or double values\n");

            } else if (str1.equals("continue")) {

                System.out.println("\nEnter the first number:");
                num1 = input.nextInt();


                System.out.println
                        ("Display:" + num1);

                System.out.println("Please enter operation:");
                operation = input.next();


                System.out.println("Enter the second number:");
                num2 = input.nextInt();
                System.out.println("Display:" + num2);


                if ("+".equals(operation)) {

                    System.out.println((num1 + num2));
                } else if ("-".equals(operation)) {

                    System.out.println((num1 - num2));
                } else if ("/".equals(operation)) {

                    System.out.println((num1 / num2));
                } else if ("*".equals(operation)) {

                    System.out.println((num1 * num2));
                } else if ("-x".equals(operation)) {

                    System.out.println(-num1);
                } else if ("x^2".equals(operation)) {

                    System.out.println(num1 * num1);
                } else if ("sqrt".equals(operation)) {

                    System.out.println(Math.sqrt(num1));

                }


            }

        }
    }
}

To check for the validity of number by implementing a try-catch , you could try to do something like this: 要通过实现try-catch来检查数字的有效性,您可以尝试执行以下操作:

try{
    Double num = Double.parseDouble(input.nextLine()); // This is just a sample
    // int someInt = Integer.parseInt(someBasString); // Even this will throw NFE
}catch(NumberFormatException NFE){ // If its not a valid number, you'll get this exception
    // Do something on error
}

You can use this 你可以用这个

try{
num1 = input.nextInt();
..
num2 = input.nextInt();
}
catch(Exception ex)
{
  System.out.println("Invalid input")
}

to make it better before catching 'Exception' you can catch 'InputMismatchException' or any other exception that you are expecting .That way you can show a more relevant info from catch. 为了在捕获“异常”之前变得更好,您可以捕获“ InputMismatchException”或您期望的任何其他异常。这样,您可以显示来自catch的更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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