[英]Java returning null and result
有人可以看看这个例子并告诉我为什么我得到 null10 作为打印值而不是 10 吗?
并且在不使用全局字符串变量“word”的情况下,该程序是否有更简单的解决方案
public class UserInput {
public static String word;
public static class TextInput {
public void add(char c) {
word = word + c;
}
public static String getValue() {
return word;
}
}
public static class NumericInput extends TextInput {
@Override
public void add(char c) {
if (Character.isDigit(c)){
word = word + c;
}
}
}
public static void main(String[] args) {
TextInput input = new NumericInput();
input.add('1');
input.add('a');
input.add('0');
System.out.println(input.getValue());
}
}
编辑:我需要使用继承自 TextInput
你需要给你的静态word
字段一个初始值,否则它会默认为null
。 当 Java 连接 String 对象时,它会将null
引用视为文字字符串“null”。 所以你实际上总是从字符串“null”开始。
如果你给你的类字段一个""
(空字符串)的起始值,那么你的代码应该按照你的期望执行。
关于这样做的更好方法,我会改为为该类提供一个StringBuilder
类型的非静态字段(并对其进行初始化,使其不为null
)。 然后您的add
方法可以简单地append(c)
新字符到StringBuilder
字段对象,这将比重复使用字符串连接(这是您使用word + c
)更有效。
您没有初始化input
,所以它是null
。 您需要先初始化input
才能进行连接工作。
所以,使用这个:
public static String word = "";
您应该使用实例变量,而不是使用在 TextInput 类的所有实例和子类中共享的静态变量。
你仍然需要初始化一个非空值
那看起来像
public static class TextInput {
protected String word;
public TextInput() {
this.word = "";
}
public void add(char c) {
word = word + c;
}
public String getValue() {
return word;
}
}
为了更好地理解问题,请尝试使用此代码
TextInput input = new TextInput();
input.add('a');
System.out.println(input.getValue());
TextInput input2 = new NumericInput();
input2.add('1');
input2.add('0');
System.out.println(input2.getValue());
另外,请参阅关于使用 StringBuilder 的@Bobulous 评论
您没有初始化“单词”。
public class TextInput {
public static String word=""; // a lil change here
public static class TextInput {
public void add(char c) {
word += c;
}
public String getValue() {
return word;
}
}
public static class NumericInput extends TextInput {
public void add(char c) {
if (Character.isDigit(c)){
word += c;
}
}
}
public static void main(String[] args) {
NumericInput input = new NumericInput();
input.add('1');
input.add('a');
input.add('0');
System.out.print(input.getValue());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.