上下文:我正在尝试创建“鹦鹉”,并为其设置年龄,名称和两个短语。
为鹦鹉提供名字后,它会问您要教他的短语,然后询问您该鹦鹉之后的下一个短语。
鹦鹉出生时会被赋予一个名字,并且知道一个短语:“ AWK!我的名字是”。由于是新鹦鹉,年龄为0,另外2个字符串为空
我的代码如下,其中有一个Parrot类和一个ParrotRunner
import java.util.*;
import java.util.Scanner;
public class Parrot {
private int age;
private String nameS;
private String nameA;
private String nameF = nameS + nameA;
private String phrase2, phrase3;
public Parrot(){
age = 0;
nameA = "Steve";
phrase2 = "";
phrase3 = "";
}
public Parrot(String na, int a , String p2, String p3){
na = nameA;
a = age;
p2 = phrase2;
p3 = phrase3;
}
public void setPhrase2(String p2){
p2 = phrase2;
}
public void setPhrase3(String p3){
p3 = phrase3;
}
public void setName(String na){
na = nameA;
}
public void presetPhrases(String nf, String ns){
nameF = nf;
nameS = ns;
}
public void setAge(int a){
a = age;
}
public String getName(){
return nameA;
}
public int getAge(){
return age;
}
public String getPhrase2(){
return phrase2;
}
public String getPhrase3(){
return phrase3;
}
public String getNameS(){
return "AWWWWWK! My name is ";
}
public String getNameF(){
return getNameS() + getName();
}
public String toStringIntroduction(){
return "AWWWWK! I'm " + getAge() + getNameF() + ". What do you wish me to say?";
}
public String toString2(){
return getPhrase2() +"! What's the other phrase?";
}
public String toString3(){
return getPhrase3();
}
}
import java.util.*;
import java.util.Scanner;
public class ParrotRunner {
public static void main(String[] args)
{
Parrot basic = new Parrot();
Scanner input = new Scanner(System.in);
int a; String p2, p3, na;
System.out.println("Provide a name");
na = input.nextLine();
System.out.println("Enter the age: ");
a = input.nextInt();
p2 = input.nextLine();
p3 = input.nextLine();
Parrot parameters = new Parrot( na, a, p2, p3);
System.out.println(parameters.toStringIntroduction());
p2 = input.nextLine();
System.out.println(parameters.toString2());
p3 = input.nextLine();
System.out.println(parameters.toString3());
}
}
有问题的代码不断出现以下错误输出,经过数小时的检查和更改我的代码后,我无法对其进行调试
ParrotRunner.main({ });
Provide a name
Name
Enter the age:
1
AWWWWK! I'm 0AWWWWWK! My name is null. What do you wish me to say?
Hi
null! What's the other phrase?
Hi
null
如果您能提供帮助,我将不胜感激,请解释为空
答案 0 :(得分:3)
public Parrot(String na, int a , String p2, String p3){
na = nameA;
a = age;
p2 = phrase2;
p3 = phrase3;
}
应该相反:
public Parrot(String na, int a, String p2, String p3){
nameA = na;
age = a;
phrase2 = p2;
phrase3 = p3;
}
您不想覆盖参数值,而是想使用它们来设置字段。确保也纠正设置者。
如果您感到困惑,请在字段名称前使用this
-该字段应始终显示在作业的左侧:
this.nameA = na;