gpt4 book ai didi

java - 关于Java中的一些简单的异常处理

转载 作者:行者123 更新时间:2023-12-01 11:57:12 25 4
gpt4 key购买 nike

有几个问题想请教,请引用我在代码中添加的注释部分,谢谢。

package test;

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

public class Test {
/* Task:
prompt user to read two integers and display the sum. prompt user to read the number again if the input is incorrect */

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

boolean accept_a = false;
boolean accept_b = false;
int a;
int b;

while (accept_a == false) {
try {
System.out.print("Input A: ");
a = input.nextInt(); /* 1. Let's enter "abc" to trigger the exception handling part first*/

accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine(); /* 2. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it? */

}
}

while (accept_b == false) {
try {
System.out.print("Input B: ");
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) { /*3. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception? */

System.out.println("Input is Wrong");
input.nextLine();
}

}
System.out.println("The sum is " + (a + b)); /* 4. Why a & b is not found?*/

}
}

最佳答案

  1. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it?

input.nextInt(); 之后使用 input.nextLine(); 是为了清除输入流中的剩余内容,因为(至少)新行字符仍在缓冲区中,如果没有首先清除,则将内容保留在缓冲区中将导致 input.nextInt(); 继续抛出 Exception

  1. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception?

可以,但是如果输入 b 错误怎么办?是否要求用户重新输入输入a?如果你有 100 个输入,而最后一个输入错误,会发生什么?实际上,你最好编写一个方法来执行此操作,即提示用户输入一个值并返回该值的方法

例如...

public int promptForIntValue(String prompt) {
int value = -1;
boolean accepted = false;
do {
try {
System.out.print(prompt);
value = input.nextInt();
accepted = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine();
}
} while (!accepted);
return value;
}
  1. Why a & b is not found?

因为它们尚未初始化,编译器无法确定它们是否具有有效值...

尝试将其更改为类似的内容。

int a = 0;
int b = 0;

关于java - 关于Java中的一些简单的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28359057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com