这个问题已经在这里有了答案: > How do I compare strings in Java? 23个
> variable access outside of if statement 4个
抱歉,这听起来很愚蠢,但是我似乎无法弄清楚如何使用在If语句中定义的变量.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//Prompt for Enchantment Type
System.out.println("Armor/Tool/Weapon");
//Wait for response
String input1 = scanner.nextLine();
if(input1 == "Armor"){
int type = 0;
}
else if(input1 == "Tool"){
int type = 1;
}
else if(input1 == "Weapon"){
int type = 2;
}
else {
int type = 3;
}
//This is where I need to access the type int
if(type == 1){
}
}
}
我无法弄清楚如何在代码块之外使用类型字符串.我知道我应该阅读范围和内容,但是我真的很希望有人能向我解释一下.
解决方法:
>在if范围之外声明变量
>使用.equals比较字符串
固定代码:
String input1 = scanner.nextLine();
int type; // scope
if(input1.equals("Armor")){
int type = 0;
}
else if(input1.equals("Tool")){
int type = 1;
}
else if(input1.equals("Weapon")){
int type = 2;
}
else {
int type = 3;
}
//This is where I need to access the String type
if(type == 1){
}
请注意,您还可以使用switch语句(仅在Java 7中!):
switch(input1) {
case "Armor":
type = 0;
break;
case "Tool":
type = 1;
break;
...
另外,在您的情况下,您可以尝试indexOf:
import java.util.Arrays;
List types = Arrays.asList("Armor", "Tool", "Weapon");
int type = types.indexOf(input1);
if (type == -1) type = 3; // if it's not found
标签:java
来源: https://codeday.me/bug/20191011/1891459.html