gpt4 book ai didi

java - 找不到符号 - 变量

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

我是 Java 新手,我正在尝试获取用户输入,将每行输入存储为变量,然后返回每个值,以便可以将其传递到其他地方。当我尝试编译时,它告诉我它找不到变量大小。我猜它也找不到其他人。我猜测这是因为我已经在“try”内部声明了变量,但不知道如何获取它以便 return 语句接受它们。代码如下:

 public Earthquake userAddEarthquake()
{

Scanner scanner = new Scanner(System.in);
try{
// convert the string read from the scanner into Integer type
System.out.println("Please Enter An Earthquake Magnitude: ");
Double magnitude = Double.parseDouble(scanner.nextLine());
System.out.println("Please Enter The Earthquakes Latitude Position: ");
scanner = new Scanner(System.in);
Double positionLatitude = Double.parseDouble(scanner.nextLine());
System.out.print("Please Enter The Earthquakes Longitude Position: ");
scanner = new Scanner(System.in);
Double positionLongitude = Double.parseDouble(scanner.nextLine());
System.out.print("Please Enter The Year That The Earthquake Occured: ");
scanner = new Scanner(System.in);
int year = Integer.parseInt(scanner.nextLine());
System.out.println("Magnitude = " + magnitude);
}

catch(NumberFormatException ne){
System.out.println("Invalid Input");
}
finally{
scanner.close();

}

return new Earthquake(magnitude, positionLatitude, positionLongitude, year);
}

最佳答案

您正在 try block 内声明大小。

try {
Double magnitude
//magnitude will only be visible inside try block
}

所以你必须在 try 之外声明它:

public Earthquake userAddEarthquake() {

Scanner scanner = new Scanner(System.in);
Double magnitude = Double.MIN_VALUE; //with a default value
try{
// convert the string read from the scanner into Integer type
System.out.println("Please Enter An Earthquake Magnitude: ");
magnitude = Double.parseDouble(scanner.nextLine());
System.out.println("Please Enter The Earthquakes Latitude Position: ");
scanner = new Scanner(System.in);
Double positionLatitude = Double.parseDouble(scanner.nextLine());
System.out.print("Please Enter The Earthquakes Longitude Position: ");
scanner = new Scanner(System.in);
Double positionLongitude = Double.parseDouble(scanner.nextLine());
System.out.print("Please Enter The Year That The Earthquake Occured: ");
scanner = new Scanner(System.in);
int year = Integer.parseInt(scanner.nextLine());
System.out.println("Magnitude = " + magnitude);
}

catch(NumberFormatException ne){
System.out.println("Invalid Input");
}
finally{
scanner.close();

}

return new Earthquake(magnitude, positionLatitude, positionLongitude, year);
}

关于java - 找不到符号 - 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19703029/

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