The Program still throws an InputMismatchException and exits even though its been caught

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

The Program still throws an InputMismatchException and exits even though its been caught

问题

import java.util.InputMismatchException;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    //init variables
    String name = "";
    int age = -1;
    int height_in_cm = -1;

    //Init Scanner
    Scanner input = new Scanner(System.in);

    //Get the input from the user and save to the initiated variables above.
    System.out.print("Please enter your name: ");
    name = input.nextLine();
    try{
    System.out.printf("Hey, %s. How old are you?: ", name);
    age = input.nextInt();
    } catch (InputMismatchException e){
        System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ", name);
        age = input.nextInt();
    }
    System.out.print("And finally, what is your height in CM?: ");
    height_in_cm = input.nextInt();

    //close the scanner to protect from resource leaks.
    input.close();


  }
}```

<details>
<summary>英文:</summary>

I am just learning Java and I&#39;m struggling with Exception handling. I am trying to write a quick program that takes some inputs and exports them converted into different units. 

I am using Scanner to take the input and I&#39;m trying to protect against an InputMisatchException but despite putting a try-catch block around it to handle the exception it still exits. the code is bellow. Hope you can help! Thanks in advance.

```import java.io.*;
import java.util.InputMismatchException;

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    //init variables
    String name = &quot;&quot;;
    int age = -1;
    int height_in_cm = -1;

    //Init Scanner
    Scanner input = new Scanner(System.in);

    //Get the input from the user and save to the initiated variables above.
    System.out.print(&quot;Please enter your name: &quot;);
    name = input.nextLine();
    try{
    System.out.printf(&quot;Hey, %s. How old are you?: &quot;, name);
    age = input.nextInt();
    } catch (InputMismatchException e){
        System.out.printf(&quot;Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: &quot;, name);
        age = input.nextInt();
    }
    System.out.print(&quot;And finally, what is your height in CM?: &quot;);
    height_in_cm = input.nextInt();

    //close the scanner to protect from resource leaks.
    input.close();


  }
}```

</details>


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

你需要在以下代码周围添加一个额外的 try-catch 块:

```java
height_in_cm = input.nextInt();

否则,你将会得到另一个异常!

英文:

You need an additional try-catch around

height_in_cm = input.nextInt();

Or else you'll get another exception!

答案2

得分: 0

以下是您要翻译的内容:

异常的原因是,在第一次抛出异常时,扫描器(input)不会更新其指针,因此catch块中的input.nextInt()读取的是与try块中的input.nextInt()相同的输入。

为了解决这个问题,在catch块中在读取int值之前添加input.nextLine()

try {
    System.out.printf("嘿,%s。你多大了?:", name);
    age = input.nextInt();
} catch (InputMismatchException e) {
    System.out.printf("啊!抱歉,%s。我们期望输入一个由0-9之间的数字组成的数字。能再试一次吗?\n你多大了?:", name);
    input.nextLine();
    age = input.nextInt();
}
英文:

The reason for the exception is that when the exception is thrown for the first time the Scanner (input) does not update its pointer, so the input.nextInt() in the catch block reads the same input as the input.nextInt() of the try block.

To resolve this, add input.nextLine() in the catch block before reading the int value.

 try{
		System.out.printf(&quot;Hey, %s. How old are you?: &quot;, name);
		age = input.nextInt();
	} catch (InputMismatchException e){
		System.out.printf(&quot;Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: &quot;, name);
		input.nextLine();
		age = input.nextInt();
	}

答案3

得分: 0

代码部分不要翻译,只返回翻译好的部分:

"The reason is that you are catching the error in the catch block. Try to implement a loop for it. Also remember to clear the buffer using input.next(); otherwise you will encounter infinite-loop

do
{
try
{
System.out.printf("嘿,%s。你多大了?:", name);
age = input.nextInt();
stop = true;
}
catch (InputMismatchException e)
{
System.out.printf("啊!对不起%s。我们期望输入一个由0-9之间的数字组成的数字。再试一次好吗?\n你多大了?:", name);
input.next(); // 清空缓冲区。否则会导致无限循环
}
} while( !stop );"

英文:

The reason is that you are catching the error in the catch block. Try to implement a loop for it. Also remember to clear the buffer using input.next(); otherwise you will encounter infinite-loop

do
{
    try
    {
        System.out.printf(&quot;Hey, %s. How old are you?: &quot;, name);
        age = input.nextInt();
        stop = true;
    } 
    catch (InputMismatchException e)
    {
        System.out.printf(&quot;Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: &quot;, name);
        input.next(); // Clearing the buffer. This is important otherwise Infinite Loop will occur
    }
} while( !stop );

huangapple
  • 本文由 发表于 2020年10月11日 16:03:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64301824.html
匿名

发表评论

匿名网友

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

确定