具有用户输入值的返回0的问题可以是任何数字

时间:2017-03-19 00:42:25

标签: java

我正在为类调试工作,我已经完成了它的调试部分,并且他已经隐藏了最后一次调试,在输出中返回零。无论您输入什么输入,它都将始终返回零。

我感觉它与“public void display()方法有关”如果有人可以给我一些关于我可以查看和排除故障的指导,我将非常感激。

// A PhoneBook is a Book with a city
import java.util.Scanner;

public class DebugPhoneBook {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String area;
    int pages;

    System.out.println("Enter city for phone book");
    area = input.nextLine();

     System.out.println("Enter number of pages in " + area + "'s phone      book");
    pages = input.nextInt();

    PhoneBook pb = new PhoneBook(area, pages);

    pb.display();
 }
 }

 //***************************************************
 //**  PhoneBook class starts below this box   **
 //***************************************************
  class PhoneBook extends Book {



  final private String area;
  final private String size;


   public PhoneBook(String city,int pages ) {
    super(pages);
    area = city;
    if (pages > 300) {
        size = "big";
    } else {
        size = "small";
    }
    }

   public void display() {
    System.out.println("The phone book for " + area
            + " has " + pages + " pages.\nThat is a "
            + size + " phone book.");
   }
}

  //******************************************************
  //** Book class starts below this box                 **
  //******************************************************
 class Book {

 protected int pages;

 public Book(int pgs) {
    pgs = pages;
 }

 public int getPages() {
    return pages;
 }
}

3 个答案:

答案 0 :(得分:3)

您的Book构造函数不会存储您传递给它的值:

public Book(int pgs) {
    pgs = pages;
}

pages(或任何int)的默认值为0。更不用说设置pgs这样的事实并没有做任何事情,因为它通过值传递给方法。

我怀疑你的意思是反过来这样做:

public Book(int pgs) {
    pages = pgs;
}

答案 1 :(得分:0)

查看Book的构造函数 而不是

public Book(int pgs) {
    pgs = pages;
}

应该是

 public Book(int pgs) {
    pages = pgs;
 }

答案 2 :(得分:0)

教授设置了这样的代码并让我们纠正了代码中的小问题。感谢您的回复,它解决了这个问题。

//***************************************************
//**  PhoneBook class starts below this box   **
//***************************************************
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("The phone book for " + area
            + " has " + pages + " pages.\nThat is a "
            + size + " phone book.");
}
}

//******************************************************
//** Book class starts below this box                 **
//******************************************************
class Book {

protected int pages;

public Book(int pgs) {
    pgs = pages;
}

public int getPages() {
    return pgs;
}
}