gpt4 book ai didi

Java对象数组似乎为空

转载 作者:行者123 更新时间:2023-12-01 18:26:16 25 4
gpt4 key购买 nike

我在使用学校 Java 程序时遇到问题,您能帮我吗?该程序应该让你在输入中给他一些书籍信息,例如每本书的标题、价格。现在我创建了一个对象数组,每个对象应该为每个选项都有一个私有(private)变量(使用方法 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 是输入字符串的方法。具有 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;
}
}

最佳答案

每次设置属性时,您都会重新创建并重置当前元素,就像这样

info[i] = new Libri2();

给您留下一组仅包含价格的对象。

关于Java对象数组似乎为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com