2016-10-01 36 views
1

我不明白为什么Sp1.location返回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.*; 

这是我的其他类

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

由于您没有设置location,你要分配输入pokemon,而不是iniLocation,当你调用函数来获取位置你得到iniLocation的值没有被赋予任何值,因此为空。阅读代码

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); 
    } 
} 
相关问题