java - 为什么初始化字符串后得到 null?

标签 java string null println

我不明白为什么 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) {


    }

}

最佳答案

因为您没有设置 location ,所以您将输入分配给 pokemon 而不是 iniLocation 当您调用函数来获取位置时,您将返回 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);
  }
}

关于java - 为什么初始化字符串后得到 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806347/

相关文章:

java - 如何将 arrayList 大小设置为 null?

java - 通过命令行或在指定时间自动触发 Eclipse clean

c++ - _mm_cmpistri 反向

java - Android 应用程序位图的替代方案

java - 查找 String 数组中索引处元素的子字符串

c - 将字符串分组到结构中

c++ - 'auto t = new decltype(nullptr)' 是做什么的?

java - 迭代时如何处理数组中的 null

java - Java 中的多播不起作用

java - 如何改进朴素贝叶斯的特征选择?