如何在 Switch 语句中捕获用户输入的数字不存在的错误。

huangapple go评论67阅读模式
英文:

How to catch an Error in a Switch statement when the user entered number doesn't exist

问题

我试图使我的程序防错,该程序基本上是一个迷你计算器。但我不知道如何编写一个“Catch”语句,以便在用户输入不存在的情况下(在我的情况下为任何负数或大于4的数字)进行检测。

public static void main(String[] args) {
    System.out.println("你好用户!你想要使用哪种操作?");
    System.out.println("1) + \n2) - \n3) * \n4) /");
    
    Scanner operacijai = new Scanner(System.in);
    int operacija = operacijai.nextInt();
    
    int n = 1;
    do {
        try {
            switch (operacija) {
                case 1:
                    addingMethod();
                    n = 2;
                    break;
                    
                case 2:
                    subtractingMethod();
                    n = 2;
                    break;
                    
                case 3:
                    multiplyingMethod();
                    n = 2;
                    break;
                    
                case 4:
                    dividingMethod();
                    n = 2;
                    break;
            }
        } catch (Exception e) {
            System.out.print("请输入正确的数字!");
        }
    } while (n == 1);
    operacijai.close();
}
英文:

I'm trying to error proof my program that basically works as a mini calculator. But I have no idea how to write a "Catch" statement that would detect when the user enters a case number that doesn't exist, in my case anything that is negative or > 4

		System.out.println("Hello user! Which operation would you like to use?");
		System.out.println("1) + \n2) - \n3) * \n4) /");
			
		
		Scanner operacijai = new Scanner(System.in);
		int operacija = operacijai.nextInt();
		
		
		int n=1;
		do {
		try {
			switch (operacija) {
			case 1:
				addingMethod();
				n=2;
				break;
					
			case 2:
				subtractingMethod();
				n=2;
				break;
				
			case 3:
				multiplyingMethod();
				n=2;
				break;
				
			case 4:
				dividingMethod();
				n=2;
				break;
					} 		
			}
			catch(Exception e) {
				System.out.print("Enter a correct number!");
			}
	
		} while(n==1);
		operacijai.close();
		
	} ```

</details>


# 答案1
**得分**: 2

为什么你要不必要地抛出一个 `Exception`?我建议你在 `switch` 中加入一个带有所需错误消息的 `default` 情况。另外,将输入部分移动到循环内,这样它就会继续获取输入。

我还建议你使用 `nextLine()` 而不是 `nextInt()`。了解更多信息,请查看 https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo。

```java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello user! Which operation would you like to use?");
        System.out.println("1) + \n2) - \n3) * \n4) /");
        Scanner operacijai = new Scanner(System.in);
        int operacija = 0, n = 1;
        boolean valid;
        do {
            do {
                valid = true;
                try {
                    operacija = Integer.parseInt(operacijai.nextLine());
                } catch (NumberFormatException e) {
                    System.out.println("Enter an integer only.");
                    valid = false;
                }
            } while (!valid);
            switch (operacija) {
                case 1:
                    System.out.println("addingMethod()");
                    n = 2;
                    break;

                case 2:
                    System.out.println("subtractingMethod()");
                    n = 2;
                    break;

                case 3:
                    System.out.println("multiplyingMethod()");
                    n = 2;
                    break;

                case 4:
                    System.out.println("dividingMethod()");
                    n = 2;
                    break;
                default:
                    System.out.println("Invalid input");
            }
        } while (n == 1);
    }
}

一个示例运行:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
5
Invalid input

另一个示例运行:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()
英文:

Why do you want to throw an Exception unnecessarily? I suggest you just put a default case in your switch with the required error message. Also, move the input part inside the loop, so that it continues to take input.

I also suggest you use nextLine() instead of nextInt(). Check https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo to learn more about it.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		System.out.println(&quot;Hello user! Which operation would you like to use?&quot;);
		System.out.println(&quot;1) + \n2) - \n3) * \n4) /&quot;);
		Scanner operacijai = new Scanner(System.in);
		int operacija = 0, n = 1;
		boolean valid;
		do {
			do {
				valid = true;
				try {
					operacija = Integer.parseInt(operacijai.nextLine());
				} catch (NumberFormatException e) {
					System.out.println(&quot;Enter an integer only.&quot;);
					valid = false;
				}
			} while (!valid);
			switch (operacija) {
			case 1:
				System.out.println(&quot;addingMethod()&quot;);
				n = 2;
				break;

			case 2:
				System.out.println(&quot;subtractingMethod()&quot;);
				n = 2;
				break;

			case 3:
				System.out.println(&quot;multiplyingMethod()&quot;);
				n = 2;
				break;

			case 4:
				System.out.println(&quot;dividingMethod()&quot;);
				n = 2;
				break;
			default:
				System.out.println(&quot;Invalid input&quot;);
			}
		} while (n == 1);
	}
}

A sample run:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
5
Invalid input

Another sample run:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()

答案2

得分: 0

你还可以处理在default中的使用情况。完全取决于您的用例,您可以如下处理异常,还可以创建自定义异常并从default中抛出,类似于:

System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) 加法\n2) 减法\n3) 乘法\n4) 除法");

Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();

int n=1;
do {
    try {
        switch (operacija) {
            case 1:
                addingMethod();
                n=2;
                break;

            case 2:
                subtractingMethod();
                n=2;
                break;

            case 3:
                multiplyingMethod();
                n=2;
                break;

            case 4:
                dividingMethod();
                n=2;
                break;
            default:
                System.out.print("输入正确的数字!");
                throw new CustomException();
        }       
    }
    catch(CustomException e) {
        System.out.print("输入正确的数字!");
    }

} while(n==1);
operacijai.close();

注意:这里的代码只是翻译了您提供的部分内容,并没有对代码逻辑进行任何更改。

英文:

You can also handle the use case in default
It is totally upto your use-case how you are handling the exception, you can also create your custom exception and throw from default
something like:

    System.out.println(&quot;Hello user! Which operation would you like to use?&quot;);
    System.out.println(&quot;1) + \n2) - \n3) * \n4) /&quot;);


    Scanner operacijai = new Scanner(System.in);
    int operacija = operacijai.nextInt();


    int n=1;
    do {
    try {
        switch (operacija) {
        case 1:
            addingMethod();
            n=2;
            break;

        case 2:
            subtractingMethod();
            n=2;
            break;

        case 3:
            multiplyingMethod();
            n=2;
            break;

        case 4:
            dividingMethod();
            n=2;
            break;
        default:
            System.out.print(&quot;Enter a correct number!&quot;)
            throw new CustomException();
        }       
      }
      catch(CustomException e) {
          System.out.print(&quot;Enter a correct number!&quot;);
      }

    } while(n==1);
    operacijai.close();

}

答案3

得分: 0

已找到一种使用默认情况的清晰方法。

public static void main(String[] args) {
    System.out.println("你好!请选择要使用的操作:");
    System.out.println("1) 加法\n2) 减法\n3) 乘法\n4) 除法");

    Scanner operacijai = new Scanner(System.in);
    int operacija;

    do {
        operacija = operacijai.nextInt();
        switch (operacija) {
            case 1:
                addingMethod();
                break;

            case 2:
                subtractingMethod();
                break;

            case 3:
                multiplyingMethod();
                break;

            case 4:
                dividingMethod();
                break;

            default:
                System.out.print("请输入正确的数字!");
        }

    } while (operacija < 1 || operacija > 4);
    operacijai.close();
}
英文:

Figured out a clean way of doing this with default case.

		System.out.println(&quot;Hello user! Which operation would you like to use?&quot;);
		System.out.println(&quot;1) + \n2) - \n3) * \n4) /&quot;);
			
		
		Scanner operacijai = new Scanner(System.in);
		int operacija;
		
		do {
			operacija = operacijai.nextInt();
			switch (operacija) {
			case 1:
				addingMethod();
				break;
					
			case 2:
				subtractingMethod();
				break;
				
			case 3:
				multiplyingMethod();
				break;
				
			case 4:
				dividingMethod();
				break;
				
			default:
					System.out.print(&quot;Enter a correct number!&quot;);
				
					} 		
	
		} while(operacija &lt; 1 || operacija &gt; 4);
		operacijai.close();
		
	}

</details>



huangapple
  • 本文由 发表于 2020年4月6日 02:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/61047815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定