我真的陷入了我的代码的末尾,这是我迷失的地方片段 . 我的目标是从我制作的一个名为Books的类(未显示)中创建一个对象数组 . 它存储他们的ISBN, Headers 和价格 . 该代码应该向用户询问书名和ISBN#,如果它与数组中的任何书籍相匹配,则具有相同ISBN和 Headers 的所有书籍将从最低价格到最高价格排序,然后全部他们的价格将改为最低价格的书的价格 . 我评论了我迷路的地方 . 非常感谢!
books类看起来像这样:class Books {private String title; private int ISBN;私人价格;
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);
}
}
3 回答
考虑以下策略:
遍历数组中的每个book对象,并检查它是否与用户输入匹配 .
如果图书匹配,请将其存储为第一遍案例的初始值's index in an array for later use and update the value for a global min price variable if the book has a lower price than what it was previously set to (control it' s)
完成列表的迭代后,使用存储每个匹配书籍索引的数组,并使用全局最小价格变量更新其价格字段
感谢大家的帮助,我想出了如何让我的程序在Jeff Ward和Phillip的帮助下做我想做的事 . 新的WORKING代码如下! :)
问题是你正在迭代不同长度的数组导致ArrayIndexOutOfBounds .
如果您输入“Lovely Bones”,111112,那么您将有3个匹配 .
sameBook长度总是10 .
但是SmallerLibrary长度为3(用计数器初始化)
因此,当迭代sameBook.length时,索引最终将大于SmallerLibrary.length,从而导致异常 .
您需要为SmallerLibrary中的值指定单独的索引 .