- 此问题在此处已有答案**:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?(4个答案)
1小时前关闭。
我已经在输入模块中获取了输入,并在显示模块中显示了它。理想情况下,存储在输入模块变量中的值应该根据指定的格式在显示模块中显示。但是,尽管输入了输入,在构造函数中初始化的变量的默认值还是显示在输出终端中。下面是我的代码:
import java.util.Scanner;
public class Library {
int acc_num;
String title, author;
Scanner sc = new Scanner(System.in);
Library() {
title = "";
author = "";
acc_num = 0;
}
void input() {
System.out.println("Enter the title, the name of the author and the accession number of the book in the same order.");
String title = sc.nextLine();
String author = sc.nextLine();
int acc_num = sc.nextInt();
}
void display() {
System.out.println("Accession number\tTitle\tAuthor");
System.out.println(acc_num + "\t" + title + "\t" + author);
}
void compute() {
System.out.println("Enter the number of days late");
int noOfDaysLate = sc.nextInt();
int fine = 2 * noOfDaysLate;
System.out.println("Fine: " + fine);
}
public static void main(String args[]) {
Library obj = new Library();
obj.input();
obj.compute();
obj.display();
}
}
- 我添加了构造函数
- 我试着改变模块的顺序
- 我尝试了www.example.com()和sc. nextLine()sc.next() and sc.nextLine()
1条答案
按热度按时间gjmwrych1#
input()方法中定义的变量会隐藏类字段。应该如下修改input()方法