java if中可否用int_java-使用在If语句中定义的变量?

这个问题已经在这里有了答案:            >            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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值