我正在研究我想要实现的目标。这是我的代码,这里的主要功能是读取一个file.txt,它有一个由空格分隔的整数,它们将被逐个读取。但是,我想知道......我怎样才能将整数存储在ArrayList中,但是在ArrayList的每个索引中都会有两个整数而不是一个整数?
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
int[] arr = readFile("address.txt");
System.out.println("The memory block generated is:");
System.out.println(Arrays.toString(arr));
}
// access this method in FIFO
public static int[] readFile(String file) { // this main method
try { // try and catch
File f = new File(file);
@SuppressWarnings("resource")
Scanner r = new Scanner(f); // read the file with scanner
int count = 0; // count for the integers
while(r.hasNextInt()) { // while keep reading
count++;
r.nextInt();
}
int[] array = new int[count];
@SuppressWarnings("resource")
Scanner readAgain = new Scanner(f); // read again
ArrayList<ArrayObjects> blockMem = new ArrayList<>(); // array size * we can use dynamic array
for(int i = 0; i < count; i++) {
// i want to iterate and save them
}
return array;
} catch(Exception fnf) {
System.out.println(fnf.getMessage() + "The file could not be open, try again");
System.exit(0);
}
return null;
} // method closed
}`
答案 0 :(得分:0)
创建一个包含两个整数的新类。
class TwoIntegers{
int one,two;
TwoIntegers(int data1,int data2){
one = data1;
two = data2;
}
}
现在创建一个TwoIntegers类型的对象的Arraylist
ArrayList<TwoIntegers> blockMem = new ArrayList<TwoIntegers>();
//now you can iterate and insert integers you need
blockMem.add(new TwoIntegers(1,2));
blockMem.add(new TwoIntegers(3,4));