【发布时间】:2016-03-10 04:23:30
【问题描述】:
import java.util.Scanner;
public class InputTest {
static void monster() {
System.out.println("You ran into a monster!");
System.out.println("He did 10 damage!");
health -= 10;
System.out.println("You have " + health + " health left!");
}
static void potion() {
System.out.println("You ran into a potion!");
System.out.println("It healed 10 damage!");
health += 10;
System.out.println("You have " + health + " health left!");
}
static void bag() {
System.out.println("You ran into a bag!");
System.out.println("It did... Nothing!");
}
static void random() {
double random = Math.random();
if(random >= 0 && random <= 0.33) {
monster();
} else if(random >= 0.24 && random <= 0.66) {
potion();
} else {
bag();
}
}
static void turn() {
System.out.println("Do you want to go left or right?");
Scanner turn = new Scanner(System.in);
String leftOrRight = turn.nextLine();
if(leftOrRight.equals("Right")) {
System.out.println("You turned right and...");
random();
} else if(leftOrRight.equals("Left")){
System.out.println("You turned left and...");
random();
} else {
System.out.println("You entered an invalid answer...");
System.exit(0);
}
}
public static void main(String[] args) {
int health = 50;
for(int i = 0; i < 10; i++) {
turn();
}
System.out.println("You won!");
}
}
这是无效的代码。 怪物();和健康();方法是我遇到麻烦的方法。 它输出我没有声明“健康”。 我明白它为什么这么说,有什么办法可以解决这个问题。 它只是不允许我在方法中使用健康整数。 如您所见,它应该取健康并减去 10。
【问题讨论】:
-
将
health设为全局变量。所以在你的怪物方法之上,做public int health = 50;。您可以让方法使用 main 中定义的健康状况。然后为health创建一个getter/setter -
@Ascalonian No. 将
health设为静态类参数。static int health = 50; -
@MikeCAT - 为什么要让它成为静态的?
-
@Ascalonian 因为它是从静态函数中使用而不创建实例。
-
嗨,德里克,欢迎来到 SO。请尝试在将来发布minimal reproducible example。这让其他人更容易回答您的问题。
标签: java variables integer declaration