显示在If语句中声明的字符串时出现问题,以下是代码:
import java.util.Scanner;
// This program reads a temp and prints its current state
public class P03_01_2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get temp
System.out.print("Enter a temperature: ");
if (in.hasNextDouble()) {
double temp = in.nextDouble();
// determine temp type and determine state
System.out.print("Enter C for Celcius or F for Fahrenheit: ");
String type = in.nextLine();
if (type.equals("c") || type.equals("C")) {
if (temp <= 0) {
String state = "frozen";
} else if (temp >= 100) {
String state = "gaseous";
} else {
String state = "water";
}
}
if (type.equals("f") || type.equals("F")) {
if (temp <= 32) {
String state = "frozen";
} else if (temp >= 212) {
String state = "gaseous";
} else {
String state = "water";
}
} else if ((!type.equals("c") || !type.equals("C") || !type.equals("f") || !type.equals("F"))) {
System.out.print("Not valid input.");
System.exit(0);
} else {
System.out.println("Not valid input.");
System.exit(0);
}
System.out.println("The state of the water is " + state);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试在第一个if语句之前添加"String state = null之前",但是一直有错误.......谢谢.
你在每个块中声明变量.即每个声明都在它自己的块中并且单独作用域.
String state = null;
if (...) {
String state = "";
// this is a different variable to 'state' outside the block!
}
Run Code Online (Sandbox Code Playgroud)
您需要在块外声明变量,然后在例如内部初始化
String state = null;
if (...) {
state = "";
}
// state is still visible here
Run Code Online (Sandbox Code Playgroud)
这是一个关于Java范围概念的简单教程.
归档时间: |
|
查看次数: |
2421 次 |
最近记录: |