为什么变量a1
没有初始化?我将其定义为if条件,但不是初始条件。
import java.util.InputMismatchException;
import java.util.Scanner;
public class Input {
static Scanner input;
public Input() {
input = new Scanner(System.in);
System.out.println("Welcome ");
}
public static Riazy GetInfo() throws InputMismatchException {
System.out.println("Enter the first Number ");
if(input.hasNextDouble()==false){
throw new InputMismatchException("Erorr...");
} else {
double a1 = input.nextDouble();
}
System.out.println("Enter the second Number ");
double a2 = input.nextDouble();
boolean a4 = input.hasNextDouble();
if(a4==false){
throw new InputMismatchException("Erorr...");
}
Riazy riazy = new Riazy(a1 , a2);
return riazy;
}
}
答案 0 :(得分:0)
像 Mike'Pomax'Kamermans 所说:“您没有正确设置变量的范围” 。
不会编译
public static Riazy GetInfo() throws InputMismatchException {
System.out.println("Enter the first Number ");
if (!input.hasNextDouble()) {
throw new InputMismatchException("Erorr...");
}
else {
double a1 = input.nextDouble();
// a1 is only accessible inside this block
}
System.out.println("Enter the second Number");
double a2 = input.nextDouble();
boolean a4 = input.hasNextDouble();
if (!a4) {
throw new InputMismatchException("Erorr...");
}
/*
* Won't compile as a1 has been defined inside the if
* else block and is not visible here
*/
return new Riazy(a1, a2);
}
编译
public static Riazy GetInfo() throws InputMismatchException {
System.out.println("Enter the first Number ");
double a1 = null; // a1 is visible in this scope
if (!input.hasNextDouble()) {
throw new InputMismatchException("Erorr...");
}
else {
a1 = input.nextDouble();
}
System.out.println("Enter the second Number");
double a2 = input.nextDouble();
boolean a4 = input.hasNextDouble();
if (!a4) {
throw new InputMismatchException("Erorr...");
}
return new Riazy(a1, a2);
}