java-使用在If语句中定义的变量?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-使用在If语句中定义的变量?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1516字,纯文字阅读大概需要3分钟。
内容图文
![java-使用在If语句中定义的变量?](/upload/InfoBanner/zyjiaocheng/693/4c1d8a989d7348dfb2e9669ad2c0e25c.jpg)
这个问题已经在这里有了答案: > 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<String> types = Arrays.asList("Armor", "Tool", "Weapon");
int type = types.indexOf(input1);
if (type == -1) type = 3; // if it's not found
内容总结
以上是互联网集市为您收集整理的java-使用在If语句中定义的变量?全部内容,希望文章能够帮你解决java-使用在If语句中定义的变量?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。