在我之前关于我的switch语句的问题之后,switch语句工作得很好,但它导致了我遇到的几个问题。
1.) 当我尝试将整数插入我的数组时,当我键入一个整数的第一个输入时它有效,它似乎在 Eclipse 上有效,但在键入第二个输入或使用 2 个不同整数的输入后。在我的解释之后,错误显示在下面。
2.) 当我在插入第一个整数以测试它是否有效后尝试打印出我的数组时,这也不是好事。也许我的ListArray类有问题?在我的解释之后,错误显示在下面,它与我的第一个问题相同。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at <my personal infomation>.ListArray.add(ListArray.java:24)
at <my personal information>.main.main(main.java:32)
3.) 我知道 .clear() 是清除数组的通用函数,但它是作为 Eclipse 上的错误引起的,即使我导入了 3 个库:
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
主代码:
public abstract class main
{
public static void main(String[] args)
{
ListArray list = new ListArray();
algorithms Alg;
Scanner s = new Scanner(System.in);
printCommands();
while(s.hasNext())
{
String command = s.next();
char ch = s.next().charAt(0);
switch(command)
{
case "c":
list.clear(); //I have found other resources that used clear() as a built in function, but Eclipse asks me to create a method?
return;
case "a":
ch = s.next().charAt(0);
list.add(ch);
break;
case "d":
System.out.println(list.toString());
break;
case "q":
s.close();
break;
default:
System.out.println("Invalid Command. Use one of the given commands.");
printCommands();
break;
}
}
}
我的列表数组类
import java.util.Arrays;
public class ListArray
{
private static final int MAX_VALUE = 0;
private Object[] myStore;
private int actSize = 0;
public ListArray()
{
myStore = new Object[MAX_VALUE];
}
public void add(Object obj)
{
int x = MAX_VALUE;
if(myStore.length-actSize <= x)
{
increaseListSize();
}
myStore[actSize++] = obj;
}
public int size()
{
return actSize;
}
private void increaseListSize()
{
myStore = Arrays.copyOf(myStore, myStore.length*2);
//System.out.println("nNew length: "+myStore.length);
}
}
此行
ListArray list = new ListArray();
假设您正在使用名称列表声明变量,其类型为 ListArray,并且您通过调用不带参数的构造器来创建实例。
问题是 - TYPE 是 ListArray。不多也不少。它是你的类,因此它只有从对象继承的方法(如equals,toString),然后只有你创建的方法。
如果不创建方法清除,则它没有方法。
如果要使用标准 Java 类,则必须声明变量,哪个类型为 1。
喜欢List<Character> x = new ArrayList<Character>();
你会得到一个 ArrayIndexOutOfBoundsException,因为数组的大小为零。
您的代码(在 ListArray
中的 add
方法中)注意到数组太小,因此它调用 increaseListSize
将大小加倍......但双零仍然是零。
然后,它尝试分配此零长度数组中的第一个元素。