我有学校Java程序的麻烦你能帮我一把吗? 该程序应该让你给他一些书籍信息的输入,如标题,每个的价格。现在我创建了一个对象Array,每个对象应该有一个私有变量用于每个选项(使用方法setter设置并使用方法getter声明)。 问题是,我不知道错误在哪里,但程序打印输出只是最后一个变量,即价格。其他都是空的。 请问你能帮帮我吗? 主:
class Esercizio2
{
public static void main(String[] args)
{
// Objects
ConsoleReader2 keyboard = new ConsoleReader2(System.in);
// Init
int n = 0; // book number
// temp variables
String title;
String writer;
String house;
String price;
// Calc
System.out.println("How many books you wanna analyze?");
do
{
n = keyboard.readInt();
if (n <= 0)
{
System.out.print("You've inserted a negative or 0 number, you have to input a positive number, try again ===> ");
}
}
while (n <= 0);
// array of the books
Libri2[] info = new Libri2[n];
// through arrays
for (int i = 0, j = 1; i < info.length; i++, j++)
{
// input title
System.out.print("Input the title for book number " + j + " ===> ");
title = keyboard.readLine();
info[i] = new Libri2();
info[i].setTitle(title);
// input writer
System.out.print("Input the writer for book number " + j + " ===> ");
writer = keyboard.readLine();
info[i] = new Libri2();
info[i].setWriter(writer);
// input house
System.out.print("Input the house for book number " + j + " ===> ");
house = keyboard.readLine();
info[i] = new Libri2();
info[i].setHouse(house);
// input price
System.out.print("Input the price for book number " + j + " ===> ");
price = keyboard.readLine();
info[i] = new Libri2();
info[i].setPrice(price);
}
// Declaration
for (int i = 0, j = 1; i < info.length; i++, j++)
{
System.out.print("The title of book number " + j + " is ===> " + info[i].getTitle() + "\n");
System.out.println("His features are:\n" + info[i].getWriter() + "\n" + info[i].getHouse() + "\n" + info[i].getPrice());
}
}
}
ConsoleReader2是一个我使用的类而不是Scanner但是同样的东西,readLine是一个输入String的方法。 使用setter和getter方法的类:
public class Libri2
{
// attributs:
private String title;
private String writer;
private String house;
private String price;
// methods: (setter e getter)
// give title
public String getTitle()
{
return this.title;
}
// set title
public void setTitle(String m)
{
this.title = m;
}
// give writer
public String getWriter()
{
return this.writer;
}
// set writer
public void setWriter(String m)
{
this.writer = m;
}
// give house
public String getHouse()
{
return this.house;
}
// set house
public void setHouse(String m)
{
this.house = m;
}
// give price
public String getPrice()
{
return this.price;
}
// set price
public void setPrice(String m)
{
this.price = m;
}
}
答案 0 :(得分:4)
每次设置属性时,您都会重新创建并重置当前元素,la
info[i] = new Libri2();
留下一系列只有价格的物品。
答案 1 :(得分:0)
将Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
放入for循环的第一行,并删除所有其他info[i]=new Libri2();
的出现。
输出错误的原因是,info[i]=new Libri2();
数组中的每个对象都被重新初始化,而每次迭代后即
Libri2[]