【发布时间】:2014-04-12 01:24:41
【问题描述】:
我真的被困在我的代码末尾,这是我迷路的地方。我的目标是从我创建的一个名为 Books 的类(未显示)中创建一个对象数组。它存储他们的 ISBN、标题和价格。该代码应该向用户询问书名和 ISBN #,如果它与数组中的任何书籍匹配,则所有具有相同 ISBN 和标题的书籍将从最低价格排序到最高价格,然后所有他们的价格将更改为最低价格的书的价格。我评论了我迷路的地方。非常感谢!
书籍类如下所示: 类书籍{ 私有字符串标题; 私人国际标准书号; 私人 int 价格;
public Books(){
title = "The Outsiders";
ISBN = 1234;
price = 14;
}
//regular constructor
public Books(String T, int I, int P){
title = T;
ISBN = I;
price = P;
}
//Copy Constructor
public Books(Books aBook){
this.title = aBook.title;
this.ISBN = aBook.ISBN;
this.price = aBook.price;
}
这是我正在学习的课程的开始:
//Beginning of ModifyBooks Class
Books[] Library = new Books[10];
Library[0] = new Books("blah", 1726374, 12.00);
Library[1] = new Books("Lovely Bones", 111112, 20.00);
Library[2] = new Books("Birds in a Fence", 111113, 13.00);
Library[3] = new Books("Hunger Games", 111114, 14.50);
Library[4] = new Books("Titanic", 738394, 12.5);
Library[5] = new Books("Heroes", 7373849, 21.00);
Library[6] = new Books(Library[1]);
Library[7] = new Books(Library[1]);
Library[8] = new Books(Library[2]);
Library[9] = new Books(Library[3]);
//Changing all prices of books
for (int i = 0 ; i < Library.length ; i++){
Library[i].price = i + 5;
}
//Keyboard configuration
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a book's title:");
String UserTitle = kb.nextLine();
System.out.println("Please enter a book's ISBN Number:");
int UserISBN = kb.nextInt();
System.out.println("Your entered book's title is " + UserTitle + " and the ISBN is " + UserISBN);
double[] sameBook = new double[10];
int counter = 0;
这是我的代码没有做我想做的事情的地方,我不知道如何让它做我上面描述的但这是我的尝试。
for (int i = 0 ; i < Library.length ; i++ ){
if (UserTitle.equalsIgnoreCase(Library[i].title) && UserISBN == Library[i].ISBN){
sameBook[i] = Library[i].price;
counter++;
}
else {
sameBook[i] = 0;
}
}
double[] SmallerLibrary = new double[counter];
for (int i = 0 ; i < sameBook.length ; i++){
if (sameBook[i] != 0){
SmallerLibrary[i] = sameBook[i];
}
}
Arrays.sort(SmallerLibrary);
}
}
【问题讨论】:
-
最后一个 for 循环没有达到我想要的效果,但我不知道如何修复它。我更好地澄清了上面的问题。
-
我假设您有两个不同的 Books 构造函数,一个接受 3 个参数,一个接受另一个 Books 对象的 1 个参数?
-
您正在将 UserISBN(用户输入时以字符串形式出现)与数组的整数 ISBN 进行比较。在比较两个 ISBN 之前,您是否将用户输入转换为整数?
标签: java arrays sorting loops object