Java:Int在获得指示后不会发生变化

时间:2017-04-08 18:09:13

标签: java

Dungeon.java

import java.util.Scanner;

public class Dungeon extends Character{
 public static void main (String[]args){
//Intro
  // Creating Relevant Objects
     Scanner Input = new Scanner(System.in);
     Character User = new Character();
     Test TT = new Test();
     Dice Rand = new Dice();
     Movement Move = new Movement();

  // Introduction
     System.out.println("Yo Yo Welcome To The Java Dungeon!");
     System.out.println("Let's Get This Party Started!");    

  // Name Input
     System.out.println("First Offf.. What Is Your Name?");
       User.CharName = Input.nextLine();
     System.out.println("Welcome " + User.CharName + "!");

  // HP Input
     System.out.println("Now Lets Get Your Health Points!");
       TT.Continue();
       User.CharHP =  Rand.Di();
     System.out.println(User.CharName + " Your HP is: " + User.CharHP);

  // Attack Input
     System.out.println("Now Lets Get Your Attack Points!");
       TT.Continue();
       User.CharAtk =  Rand.Di();
     System.out.println(User.CharName + " Your Attack Points are: " + 
User.CharAtk);

 // Dungeon Start!
     while (User.CharPos < 10 ){
         Move.Moving();


}

}



}

&安培; Character.java

    import java.util.Scanner;

public class Character {
    String CharName = "blank";
    int CharHP = 0;
    int CharAtk= 0;
    int CharPos = 0;

}

class Movement{
 public void Moving(){
//Input Object
        Scanner Input = new Scanner(System.in);
        Character User = new Character();

//Test
        char test = 'g';
         System.out.println("You Are Currently On Level: " + User.CharPos);
         System.out.println("Enter E To Move Forward");
          test = Input.next().charAt(0);
           if (test != 'e' && test != 'E'){
                 System.out.println("You've Failed Already... You Fell Into 
    a Spiky AF Pit!");
                 System.exit(0);

                 } 

           else {
               User.CharPos++;
           }
    }
}

无论我做什么,每次循环播放时,我都无法将Int CharPos增加1。这就是我之前编码的方式,但我无法看到它增加。任何时候?我还没有其他课程,但它不会对这两个课程产生影响。

1 个答案:

答案 0 :(得分:0)

@UnholySheep是对的。要解决您的问题,您需要: 1)将Character类中的Movement转换为字段,而不是在每个Move方法调用上创建新实例。 2)创建Character object ouride Movement并将其传递给Movement类实例 3)使用getter追溯字符字段

class Movement{

private Character user;

public void setCharacter(Character user)
{
    this.user = user;
}

public Character getCharacter()
{
    return user;
}

 public void Moving(){
//Input Object
        Scanner Input = new Scanner(System.in);
        .....
        user.CharPos++;
        .... 

在其他课程中:

public class Dungeon extends Character{
 public static void main (String[]args){
//Intro
  // Creating Relevant Objects
     Scanner input = new Scanner(System.in);
     Character user = new Character();
     Test tt = new Test();
     Dice rand = new Dice();
     Movement move = new Movement();
     move.setCharacter(User);
...