我試圖用幾種不同的方法打印我的數組,並且似乎已經把它搞砸了。我曾經從中得到一些東西,現在我只能得到零。如果有人知道打印陣列的方法,很容易,那會很棒。使用Array.toString似乎沒有工作出於某種原因。在java中使用long []打印數組
public class Array {
private long[] InitialArray;
private int size = 0;
/**
* the default constructor
*/
public Array(int size){
InitialArray = new long[size];
}
/**
* this will scan in integers from a file
* @param scans
*/
public Array(Scanner scans){
this(1);
int j = 0; //just used as a counter basically
while(scans.hasNext()){ //grabs each element
this.insert(Integer.parseInt(scans.nextLine())); //inserts it
j++; //steps through using the counter
}
}
/**
* this will make the array longer if more space is needed so you don't
* crash if you have a very large set of numbers
*/
public void stretch(){
long[] temp = new long[InitialArray.length *2]; //makes a temp array double the normal size
for(int i=0; i < InitialArray.length; i++)
temp [i] = InitialArray[i]; //steps through the old array to keep the data
InitialArray = temp; //assigns the temp array to the new array
}
/**
* this will insert each element read, from a file, into the array
* @param x
*/
public void insert(int x){
if (this.size+1 == InitialArray.length){ //trying not to crash
stretch(); //making sure I don't crash
}
InitialArray[size++] = x; //stepping through the numbers and inserting
sorter();
}
/**
* this is a selection sort on the array
* It's not the quickest, but it's fairly easy to build and understand
* Just finds the minimum element and swaps it to it's proper place
* @return
*/
public long[] sorter(){
for (int i=0; i<InitialArray.length-1; i++){
int minimum = i; //assigning a minimum
for (int j=i+1; j<InitialArray.length; j++){
if (InitialArray[minimum] > InitialArray[j]) { //checking to make sure it is the smallest
minimum = j; //if it isn't then do this
}
}
if (minimum != i){ //all the swapping stuff, which I never really understand but it works
long temp = InitialArray[i];
InitialArray[i] = InitialArray[minimum];
InitialArray[minimum]= temp;
}
}
return InitialArray;
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner scans;
try {
scans = new Scanner(new FileInputStream("src/some numbers.txt"));
Array InitialArray = new Array(scans);
System.out.println(InitialArray);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我不斷收到一個錯誤,說它必須是數組類型,但解析爲數組。我只是需要它來查看是否還有其他工作。
謝謝,你是對的我的排序不正確。這僅僅是爲了學習一些東西。我可以嘗試將其更改爲一個ArrayList,然後我不必擔心它的大小,並可以擺脫我的整個拉伸和一切。我會盡力做到這一點。 – Defc0n