【发布时间】:2015-06-02 22:19:27
【问题描述】:
因此,我们在课堂上遵循实验室手册的说明。我能够完成第一步和第二步,我只需要第三步的帮助。
实验室手册说明:
- 将方法 void removeFirst(int newVal) 添加到 IntegerList 类,从列表中删除第一次出现的值。如果该值没有出现在列表中,它应该什么都不做(但这不是错误)。删除一个项目不应该改变数组的大小,但请注意,数组值确实需要保持连续,所以当你删除一个值时,你必须将它之后的所有内容向下移动以填满它的空间。还要记住减少跟踪元素数量的变量。
在 IntegerListTest 的菜单中添加一个选项来测试您的新方法。
整数列表
public class IntegerList
{
private int count;
private double totalInt;
int[] list; //values in the list
//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
void addElement(int newVal)
{
if (count == list.length)
increaseSize();
list[count] = newVal;
count++;
}
void removeFirst(int newVal2)
{
for (int i = 0; i < list.length-1; i++)
{
if (newVal2 == list[i])
{
list[list.length] = (Integer) null;
list[i] = list [i-1];
}
}
}
public IntegerList(int size)
{
list = new int[size];
count = 0;
}
public void randomize()
{
for (int i=0; i<list.length; i++)
{
list[i] = (int)(Math.random() * 100) + 1;
count++;
}
}
public void print()
{
for (int i=0; i<count; i++)
System.out.println(i + ":\t" + list[i]);
}
private void increaseSize()
{
int[] temp = new int[list.length * 2];
for (int lst = 0; lst < list.length; lst++)
temp[lst] = list[lst];
list = temp;
}
}
整数列表测试
import java.util.Scanner;
public class IntegerListTest
{
static IntegerList list = new IntegerList(10);
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
printMenu();
int choice = scan.nextInt();
while (choice != 0)
{
dispatch(choice);
printMenu();
choice = scan.nextInt();
}
}
公共静态无效调度(int选择) {
int loc;
switch(choice)
{
case 0:
System.out.println("Bye! ") ;
break;
case 1:
System.out.println("How big should the list be?");
int size = scan.nextInt();
list = new IntegerList(size);
list.randomize();
break;
case 2:
list.print();
break;
case 3:
System.out.println("What number would you like to add?");
int newVal = scan.nextInt();
list.addElement(newVal);
break;
case 4:
System.out.println("What number do you want to remove? (Removes first occurance.)");
int newVal2 = scan.nextInt();
list.removeFirst(newVal2);
default:
System.out.println("Sorry, invalid choice");
}
}
public static void printMenu()
{
System.out.println("\n Menu ");
System.out.println(" ====");
System.out.println("0: Quit");
System.out.println("1: Create a new list (** do this first!! **)");
System.out.println("2: Print the list");
System.out.println("3: Add to the list");
System.out.println("4: Remove Integer");
System.out.print("\nEnter your choice: ");
}
}
非常感谢任何帮助。如果你也能解释为什么我可以从中学习,那就太酷了。谢谢! :D
【问题讨论】: