[英]In Java, Why cannot I insert an integer more than once, cannot print out after inserting one integer and cannot empty array with imported libraries?
在關於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;
}
}
}
我的ListArray類
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。 不多不少。 它是您的類,因此它確實只有從Object繼承的方法(例如equals,toString),然后只有您創建的方法。
如果不創建方法清除,則它沒有一個。
如果要使用標准Java類,則必須聲明類型為1的變量。
像List<Character> x = new ArrayList<Character>();
因為數組的大小為零,所以您獲得ArrayIndexOutOfBoundsException。
您的代碼(在ListArray
的add
方法中)注意到該數組太小,因此它調用increaseListSize
大小以將大小加倍...但雙零仍然為零。
然后,它嘗試分配此零長度數組中的第一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.