if 语句之外的变量访问 [英] variable access outside of if statement
本文介绍了if 语句之外的变量访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 java 中的 if 语句之外访问变量.变量是axeMinDmg
.这是我所拥有的,但出现错误.我想要 minDmg = axeMinDmg
.谢谢
I am trying to access variable outside an if statement in java. The variable is axeMinDmg
. Here is what i have but getting an error. I want minDmg = axeMinDmg
. thanks
@SuppressWarnings("unused")
public static void main(String[] args)
throws IOException
{
int count = 1;
// start both with 1 point
int goodTotal = 50;
int monTotal = 50;
// set amount of money that Goodman has
int moneyAmt = 10;
// setting array for bat
int [] bat = {2, 4, 3};
int batMinDmg = bat[0];
int batMaxDmg = bat[1];
int batCost = bat[2];
//setting array for axe
int [] axe = {4, 6, 6};
int axeMinDmg = axe[0];
int axeMaxDmg = axe[1];
int axeCost = axe[2];
//setting array for sword
int [] sword = {6, 8, 10};
int swordMinDmg = sword[0];
int swordMaxDmg = sword[1];
int swordCost = sword[2];
// ask if Goodman would like to purchase a weapon
System.out.println("Would you live to purchase a weapon (YES OR NO): ");
Scanner sc = new Scanner(System.in);
String name = sc.next();
if (name.equals("yes")){
System.out.println("Select Your Weapon
axe
bat
sword :
");
Scanner wc = new Scanner(System.in);
String weapon = wc.next();
int minDmg = axeMinDmg;
if(weapon.equals("axe")){
int minDmg = axeMinDmg;
} else {
System.out.println();
} // close if statement
推荐答案
您需要在 if 语句之外定义变量才能在外部使用它.
You'll need to define the variable outside of the if statement to be able to use it outside.
这篇关于if 语句之外的变量访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文