【发布时间】:2015-10-14 11:45:47
【问题描述】:
package arrayprogram;
public class ArrayProgram {
public static void main(String[] args) {
Store watchStore = new Store();
String wcome = Menu.welcome();
int opt = Integer.parseInt(wcome);
switch(opt){
case 1:
watchStore.addWatches();
for(;;){
String option = InputHelper.getInput("you want to add another watch (Y/N) ?: ");
if ("y".equalsIgnoreCase(option)) {
watchStore.addWatches();
}else{
break;
}
}
case 2:
String back = Menu.welcome();
int option = Integer.parseInt(back);
if(option == 2)
watchStore.viewWatch();
break;
case 3:
Watch found;
found = watchStore.findWatchBySerialNumber(333);
System.out.println(found);
break;
}
}
}
上面的代码包含我的主要方法,其余的类将遵循
商店类
package arrayprogram;
import java.util.ArrayList;
public class Store {
ArrayList<Watch> watchStore = new ArrayList<>();
Watch wt = new Watch();
public void addWatches(){
String name = InputHelper.getInput("Enter name: ");
String serial = InputHelper.getInput("Enter serial: ");
String desc = InputHelper.getInput("Enter description: ");
String color = InputHelper.getInput("Enter Color: ");
String price = InputHelper.getInput("Enter price: ");
String weight = InputHelper.getInput("Enter weight: ");
double pr = Double.parseDouble(price);
double wg = Double.parseDouble(weight);
long sr = Long.parseLong(serial);
wt.addWatch(name, sr, desc, color, pr, wg); // this is a method inside Watch class that is responsible for adding watch information
watchStore.add(wt);
}
public void viewWatch(){
for (int i = 0; i<watchStore.size(); i++){
System.out.println(watchStore.get(i));
}
}
public Watch findWatchBySerialNumber(long serial) {
for(Watch w : watchStore) {
if(w.getSerial() == serial) {
System.out.print("found");
return w;
}
}
System.out.print("not found");
return null;
}
public void deleteWatch(){
//the code will follow
}
public void averageWatch(){
//the code will follow
}
}
InputHelper 类
package arrayprogram;
import java.util.Scanner;
public class InputHelper {
public static String getInput(String prompt){
Scanner input = new Scanner(System.in);
System.out.print(prompt);
System.out.flush();
try{
return input.nextLine();
}
catch (Exception e){
return "Invalid entry";
}
}
}
菜单类
package arrayprogram;
public class Menu {
public static String welcome(){
return InputHelper.getInput("Welcome our watch store\n"
+ "1. Add new watch\n"
+ "2. Delete Watch by serial number\n"
+ "3. View all watches information\n"
+ "4. Search watch by serial number\n"
+ "5. View average weight of available watch\n"
+ "\n"
+ "Choice: "
);
}
}
最后,上面的程序运行得很好。但上面的程序就是这样。
我无法在数组列表中搜索具有匹配序列号的特定监视对象。
欢迎对上述程序提出任何建议。任何改进。
【问题讨论】:
-
对于第 2 部分 codereview 将是一个更好的地方
-
如果您能告诉我们您的意见是什么,那就太好了。
-
你能不能这样试试:ArrayList
watchStore = new ArrayList (); ?此外,我们想知道您的代码是如何失败的。输入是什么,您期望什么以及意外的输出是什么? -
如果我没有被那一堆代码完全弄错,那么您总是将相同的
Watch实例添加到您的ArrayList。你永远不会重新初始化你的wt变量,它奇怪地是一个类变量。您可以尝试在您的列表中找到您最新的手表,应该可以找到。 -
我不确定是否是这种情况,但在您的
getInput()中,搜索手表是#4,但在您的switch中是第 3 位。确保您输入的是#3