gpt4 book ai didi

java - 我想在 catch block 运行时打印无效输入,但它没有发生。请帮助我

转载 作者:行者123 更新时间:2023-12-01 17:12:30 27 4
gpt4 key购买 nike

如果发生输入不匹配,我想打印 catch block 中的内容。我已经为 Marathon 类编写了代码,其对象是在此处创建的。帮帮我

 import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Marathon m=new Marathon();
System.out.print("Enter name: ");
String name=sc.nextLine();
System.out.print("Enter age: ");
int age=sc.nextInt();
System.out.print("Enter Gender: ");
char gender=sc.next().charAt(0);
System.out.print("Enter Contact no: ");
long number=sc.nextLong();
try{
m.setName(name);
m.setAge(age);
m.setGender(gender);
m.setContactNo(number);
System.out.println("Registered Successfully");
}
catch(InputMismatchException e){
System.out.print("Invalid Input");
}
}

最佳答案

您需要捕获将从 try-catch block 内的输入抛出的异常

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Marathon m=new Marathon();
System.out.print("Enter Contact no: ");
try{
System.out.print("Enter name: ");
m.setName(sc.nextLine());
System.out.print("Enter age: ");
m.setAge(sc.nextInt());
System.out.print("Enter Gender: ");
m.setGender(sc.next().charAt(0));
m.setContactNo(sc.nextLong());
System.out.println("Registered Successfully");
}
catch(InputMismatchException e){
System.out.print("Invalid Input");
}
}

关于java - 我想在 catch block 运行时打印无效输入,但它没有发生。请帮助我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61415588/

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