【发布时间】:2014-01-27 08:42:24
【问题描述】:
我基本上有一个程序可以从文件中读取杂货并将它们存储在数组中。它允许用户添加项目(项目名称、项目数量)和从数组中删除项目。
但是,我在尝试编辑数组中的项目时遇到问题?所以改变它的名字和数量。
这是我添加、编辑(需要帮助)和删除的三个方法代码:
/**
* ADDS a grocery item to an array
*/
public static Integer add(String [] list, Integer listSize){
//get item from user
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of item: ");
String name = keyboard.nextLine();
System.out.print("Enter number of items: ");
String number = keyboard.nextLine();
//add to the end of the array
list[listSize] = name + ", " + number;
//add one to the size (one item to end of list)
return listSize + 1;
}
/**
* EDITS a grocery item to an array
*
* My steps to take
*1: Prompt user for row number to be replaced
*2: name of new item
*3: number of new items
*4: error checking: If the user enters a row number
* that does not exist in the list- display error message
*/
public static Integer edit(String [] list, Integer listSize){
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the row number of the item you would like to edit: ");
try{
Integer row = userInput.nextInt();
if(row <= 0){
System.out.println("ERROR: The number can't be negative or zero!");
}
//check if int is too large
else if(row > listSize-1){
System.out.println("ERROR: The number is too big for the list.");
}
else{
for(int i=row; i<listSize; i++){
list[i] = list[i+1];
}
}
System.out.print("Enter name of item: ");
String name = userInput.nextLine();
System.out.print("Enter number of items: ");
String number = userInput.nextLine();
list[listSize] = name + ", " + number;
}
catch(InputMismatchException exception){
System.out.println("ERROR: You must enter a number to edit an item.");
}
return listSize ;
}
/**
* DELETES a grocery item from an array
*/
public static Integer delete(String [] list, Integer listSize){
//get user input
System.out.print("Enter the row number of the item you wish to delete: ");
Scanner keyboard = new Scanner(System.in);
try{
//throws an exception if not an integer
Integer row = keyboard.nextInt();
//check for negative integers
if(row <= 0){
System.out.println("ERROR: The integer cannot be negative or zero.");
}
//check for integer too big
else if(row > listSize-1){
System.out.println("ERROR: The integer is too big for the list.");
}
else{
//delete item by shifting items on the right of the item to the left
for(int i=row;i<listSize;i++){
list[i] = list[i+1];
}
//subtract one from the size (one item deleted from list)
--listSize;
}
}
catch(InputMismatchException exception){
System.out.println("ERROR: You must enter an integer to delete an item.");
}
return listSize ;
}
任何帮助将不胜感激:o!
【问题讨论】:
-
您遇到问题了吗?什么问题?..
-
SO不是服务中心
:) -
你可以用ArrayList代替String Array
-
嗨,我在为我的程序创建编辑方法时遇到问题 :(。我将添加我想要实现的示例输出:o
-
请看我的回答。无论如何,您的示例输出似乎是正确的。如前所述,您应该能够描述您的问题。 “我遇到问题” 还不够。
标签: java arrays edit printwriter