我想说感谢您审核我的帖子以及我遇到的任何问题。我是java的新手所以我想知道你们是否可以帮我调试这个程序。
import java.util.Scanner;
public class DebugExercise {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String area, inStr;
int pages;
System.out.println("Please enter your city");
area = input.nextLine();
System.out.println("Please enter page number " + area + "'s phone book");
pages = input.nextInt();
PhoneBook phoneBook = new PhoneBook(area, pages);
phoneBook.display();
}
}
class PhoneBook extends Book {
private String area;
private String size;
PhoneBook(int pages, String city) {
super();
area = city;
if (pages > 300) {
size = "big";
} else {
size = "small";
}
}
public display() {
System.out.println( area + pages + size);
}
}
class Book {
protected int pages;
public Book(int pages) {
pages = pages;
}
public int getPages() {
return pages;
}
}
答案 0 :(得分:2)
将参数交换到电话簿构造函数
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String area, inStr; //there is no need of inStr as you are not using it so remove it if not used
int pages;
System.out.println("Please enter your city");
area = input.nextLine();
System.out.println("Please enter page number " + area + "'s phone book");
pages = input.nextInt();
PhoneBook phoneBook = new PhoneBook(pages,area); //swapp the argurments
phoneBook.display(pages, area); //add arguments to this otherwise it will just show 0
}
在你的电话簿课程中添加参数到super
PhoneBook(int pages, String city) {
super(pages); // u can even remove this its not needed
area = city;
if (pages > 300) {
size = "big";
} else {
size = "small";
}
public void display(int pages,String area) {
System.out.println( area + pages + size);
}
}
现在它会起作用
答案 1 :(得分:0)
首先,您有一些基本问题:
Phonebook
班级的构造函数PhoneBook(int pages, String city)
中,您调用了super()
,但是没有类Book的空构造函数,因此您必须调用super(pages)
。 Book
类的构造函数中,您正在为pages
变量分配它自己的值。你可能想要做的是this.pages = pages;
。通过使用this.pages
,您告诉java您指的是您正在创建的对象的字段pages
,而不是指向传递给构造函数的参数。您可以在Oracle的文档here this
关键字
醇>