2016-10-01 2 views
1

Sp1.locationがNULLを返す理由を理解できません。私はそれが私は場所を正常に初期化することができますシームプログラムを実行する場合。私は同様の方法で整数として属性をコードしていますが、それは問題ありませんでした。文字列を初期化した後にnullが返されるのはなぜですか?

public class Database { 

    static Scanner userInput = new Scanner(System.in); 

    public static void main(String[] args) { 

     System.out.println("Add a new spawnpoint.\n"); 

     System.out.println("State the name of this spawnpoint: "); 


     Spawnpoints Sp1 = new Spawnpoints(getSpawnName()); 

     System.out.println("Done"); 
     System.out.println("Location: " + Sp1.getLocation()); //return as null 

    } 

    public static String spawnName; 

    public static String getSpawnName() { 

     spawnName = userInput.next(); 
     return spawnName; 
    } 

    public void setSpawnName(String spawnName) { 
     this.spawnName = spawnName; 
    } 
} 


// Import libraries 
import java.util.*; 

これは、あなたがlocationを設定していないので、あなたの代わりにiniLocationpokemonへの入力を割り当て、ときに場所を取得するための関数を呼び出している私の他のクラス

public class Spawnpoints extends Database { 


     // Define scanner, so you can accept user input 
     static Scanner userInput = new Scanner(System.in); 

      // Define attributes of Spawnpoints 


      private String location; 
      private String iniLocation; 


    // Creator, method for creating a instance of Spawnpoints. Will be the actual spawnpoints 
    // I include a iniLocation so no user input is asked when calling on getLocation. 

    public Spawnpoints(String spawnName) { 
     getIniLocation(); 

    } 

    // Setters & Getters getLocation 
    private String getIniLocation() { 
     System.out.println("State the location of this spawnpoint:\n"); 
     pokemon = userInput.next(); 
     return iniLocation; 
    } 

    public void setIniLocation(String iniLocation) { 
     this.iniLocation = iniLocation; 
    } 


    public String getLocation() { 
     location = iniLocation; 
     return location; 
    } 


    public void setLocation(String location) { 
     this.location = location; 
    } 



    public static void main (String[] args) { 


    } 

} 

答えて

1

です値が割り当てられていないiniLocationの値が返されるので、nullになります。コード

private String getIniLocation() { 
    System.out.println("State the location of this spawnpoint:\n"); 
    pokemon = userInput.next(); // remove this 
    iniLocation = userInput.next(); // with this 
    return iniLocation; 
} 

のコメントを読んで、あなたは、コンストラクタであなたのscannerオブジェクトを初期化した場合、それは良い習慣です。

class AnyClass{ 
Scanner scan; 
    public AnyClass(){ 
    scan= new Scanner(System.in); 
    } 
} 
関連する問題