3 /**/ 17 39 82 108 117 8 25 47 58 63 72 99
我有这些数字。他们通过下面的程序读入字段 int [][]rag。
public class RaggedArray {
/**/
private int [][] rag;
/**/
public static void main ( String [] arg ) {
System.out.println( new RaggedArray() );
return;
}
/**/
public RaggedArray() {
initFromFile("rag.txt");
}
/**/
public String toString () {
/**/
String lf;
/*
* lf == line-feed character
*/
lf=System.lineSeparator();
/*
* Provide needed code here.
*/
}
/**/
private void initFromFile ( String fileName ) {
/**/
FileInput fi;
int numRows;
/**/
fi=new FileInput(fileName);
numRows=fi.readLineInt();
rag=new int [numRows][];
fi.readLine();
for ( int i=0; i<numRows; ++i ) rag[i]=fi.readLineInts();
fi.close();
/**/
return;
}
}
这是我到目前为止所拥有的
rag=new int [4][]
for (int i=0; i<rag.length; ++i ) {
每个 int 都应该在宽度为 4 的字段中右对齐。老实说,如果代码中包含数字,我只知道如何执行此操作。但数字在不同的文件中。有人有什么主意吗?
回答1
您可以将文件内容读入一个数字数组,然后您可以使用该数组填充二维数组。
private int[] readNums(File file){
try(BufferedReader br = new BufferedReader(file)){
String line;
if(line = br.readLine() != null){
String split = line.split(" ");
int[] ints = new int[split.length()];
for(int i = 0; i<split.length(); i++){
ints[i] = Integer.parseInt(split[i]);
}
return ints;
}
} catch(Exception e){
//catch what's needed
}
return null;
}
然后根据需要使用数字。例如,如果我理解正确,如果你想把它们放在宽度为 4 的二维数组的最右边,你可以这样做
private int[][] fillArray(int[] input){
int[][] intArray = new int[4][input.length()];
for(int i=0; i<input.length(); i++){
intArray[4][i] = input[i];
}
return intArray;
}
使用流或现代库也可以更简单地编写它,但为了简单起见,我省略了它。如果你想告诉我,我也可以添加它。