gpt4 book ai didi

Java catch Exception IllegalArguementsException 强制我启动字符串

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:03 24 4
gpt4 key购买 nike

每当我捕获整数的异常时,它都可以正常工作,但是当我尝试使用字符串值时,它希望我启动该字符串。以下是我到目前为止的代码

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
LocalMath e = new LocalMath();
Machine machine = new Machine(name);
String name;
int age;
Scanner userInput = new Scanner(System.in);
System.out.println("What is your name?");

try{
name = userInput.nextLine();
} catch (Exception IllegalArgumentException) {
System.out.println("Must be a character from the english alphabet!");
}

// System.out.println(e.add(5, 10));
System.out.println(name);
System.out.println("-------");
System.out.println("What is your age?");

try {
age = userInput.nextInt();
System.out.println(age);
} catch (Exception IllegalArgumentException) {
System.out.println("Must be in numeric value only!");
}


}
}

以及我的其余代码

public class Machine {
public Machine(){

}

public Machine(String name){

}

public Machine(int age){

}
}

最佳答案

只需将字符串变量初始化为 null

        String name = null;

由于 name 的 try/catch block 有可能在没有为其分配任何值的情况下到达 sysytem.out 行。例如,如果 userInput.nextLine() 引发非法参数异常,则不会为 name 赋值,但函数的其余部分将执行,因为异常已被捕获。异常和 catch 行之间发生的任何事情都会被跳过。因此,字符串“name”可以在分配任何内容之前使用;因此,编译器强制您显式初始化它。

如果您可以使用变量/内存地址而不保证它已被设置为一个值,您可能会发现“name”保存了上次使用该内存地址时的错误数据。编译器保证不会发生这种情况。

关于Java catch Exception IllegalArguementsException 强制我启动字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26770936/

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