如何在 if 语句中使用全局变量
我有这个 if 语句以及访问 axeMinDmg 的内容。我如何将它设置为全局变量,以便我可以在 if 语句中访问它。另外,如何将 minDmg 设置为全局变量,以便我可以在 if 语句之外进行访问。谢谢
// if yes ask what weapon to purchase
if (name.equals("yes")){
System.out.println("Select Your Weapon \n axe \n bat \n sword : \n ");
Scanner wc = new Scanner(System.in);
String weapon = wc.next();
if(weapon.equals("axe")){
minDmg = axeMinDmg;
} else {
System.out.println();
} // close if statement
I have this if statement and what to access axeMinDmg. How do i set it as a global variable to so that i can access it within the if statement. Also, how to i set minDmg as a global variable so that i can access outside of the if statement. thanks
// if yes ask what weapon to purchase
if (name.equals("yes")){
System.out.println("Select Your Weapon \n axe \n bat \n sword : \n ");
Scanner wc = new Scanner(System.in);
String weapon = wc.next();
if(weapon.equals("axe")){
minDmg = axeMinDmg;
} else {
System.out.println();
} // close if statement
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java中确实不存在全局变量。您可以创建类的公共静态最终成员,并且该成员将在与该类相同的范围内访问(如果到处都是公共的),
并且可以从任何地方用作 MyClass.axeMinDmg 。
另一种方法可能是使用 Enum。
Global variables really does not exists in Java. You can create a public static final member of a class and the member will accesible in the same scope as the class (if public everywhere)
can be used as MyClass.axeMinDmg from everywhere.
Another way could be to go with an Enum.
您可以在块外声明并初始化它
。这将允许您在 if 内使用它。
例如
希望我按预期回答你的问题。
You can declare and initialize it outside the
block. This will allow you to use it within if.
e.g.
Hope I am answering your question as intended.
您可以在类的开头初始化它,因此 if 语句将包含在其范围内。
You can initialize it in the beginning of your class, so the if statement would be included in its scope.