gpt4 book ai didi

java - 为什么我必须在这个程序中初始化a和b?

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

在这个程序中为什么我必须初始化ab ,因为它们的范围不受限制,但我不能在线上使用它们 d=a+b

import java.util.Scanner;
class DivAndSum {
public static void main(String[] args) {
int a = 0, b = 0;
Scanner kb = new Scanner(System.in);
try {
a = kb.nextInt();
b = kb.nextInt();
int c = a / b;
System.out.println("Div=" + c);
} catch (ArithematicException e) {
System.out.println("Please Enter a non zero denominator");
} catch (InputMismatchException e) {
System.out.println("Please Enter integers only");
System.exit(0);
}
int d = a + b;
System.out.println("Sum=" + d);
}
}

下面的程序可以正常编译:

import java.util.Scanner;
class DivAndSum {
public static void main(String[] args) {
int a,b,d;
Scanner kb = new Scanner(System.in);
a = kb.nextInt();
b = kb.nextInt();
d = a + b;
System.out.println("Sum=" + d);}}

最佳答案

如果您正在谈论 int a=0,b=0; 那么 ab 都是局部变量,并且局部变量有初始化

只有类级和实例级变量不需要初始化

如果您不想初始化,请参阅下面的代码

import java.util.Scanner;
class DivAndSum {
int a,b; // here a and b are instance variables so no need to be initialized. Both will have value 0 which is default
public static void main(String[] args) {
// int a = 0, b = 0; a and b are loca variables so both should be initialized
Scanner kb = new Scanner(System.in);
try {
a = kb.nextInt();
b = kb.nextInt();
int c = a / b;
System.out.println("Div=" + c);
} catch (ArithematicException e) {
System.out.println("Please Enter a non zero denominator");
} catch (InputMismatchException e) {
System.out.println("Please Enter integers only");
System.exit(0);
}
int d = a + b;
System.out.println("Sum=" + d);
}
}

关于java - 为什么我必须在这个程序中初始化a和b?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36171563/

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