我有一个二维数组,我将其命名为查找表,如下所示:
123 256 19 52369564875214
147 307 51 12654987625425
136 94 14 65913210210871
301 818 23 74120032154894
215 103 81 54680045569748
...
...依此类推(数组大小为 700x4)
这项工作的目的是要求用户输入三个数字,比如 a、b 和 c。然后,此代码应查看表(上面的数组)并返回相应的值 d,其中 d 是从最后一列中提取的。例如,如果用户输入 (147,307,51),那么代码应该给用户 12654987625425。实际上作为函数 f(a,b,c)=f(147,307,51)=12654987625425。
package arrayread;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayRead {
//
public static void main(String [] args)
{
ArrayRead ar = new ArrayRead();
ar.readArray("C:/Users/Desktop/tsp2.txt",",");
String arr[][] = ar.getArray();
int rows = ar.getRows();
int cols = ar.getCols();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
System.out.print(arr[r][c]+" ");
}
System.out.println();
}
}
private String arr[][];
private int rows, cols;
String[][] getArray()
{
return arr;
}
int getRows()
{
return rows;
}
int getCols()
{
return cols;
}
// Read using DELIMITER TAB
void readArray(String arrayName)
{
rows = 0;
cols = 0;
int r, c, numElements;
String ipString, splitString[];
ArrayList <String>tmpArr = new ArrayList<>();
try
{
Scanner in = new Scanner(new FileReader(arrayName));
while(in.hasNext())
{
ipString = in.nextLine();
splitString = ipString.split("\t");
if (rows==0)
{
cols = splitString.length;
}
for (c=0;c<cols;c++)
{
tmpArr.add(splitString[c]);
}
rows++;
}
in.close();
arr = new String[rows][cols];
numElements = 0;
for (r=0; r<rows; r++)
{
for (c=0; c<cols; c++)
{
arr[r][c] = tmpArr.get(numElements);
numElements++;
}
}
}
catch (Exception e)
{
System.out.println("Error occurred!");
}
}
// Read using DELIMITER regex
void readArray(String arrayName, String regex)
{
rows = 0;
cols = 0;
int r, c, numElements;
String ipString, splitString[];
ArrayList <String>tmpArr = new ArrayList<>();
try
{
Scanner in = new Scanner(new FileReader(arrayName));
while(in.hasNext())
{
ipString = in.nextLine();
splitString = ipString.split(regex);
if (rows==0)
{
cols = splitString.length;
}
for (c=0;c<cols;c++)
{
tmpArr.add(splitString[c]);
}
rows++;
}
in.close();
arr = new String[rows][cols];
numElements = 0;
for (r=0; r<rows; r++)
{
for (c=0; c<cols; c++)
{
arr[r][c] = tmpArr.get(numElements);
numElements++;
}
}
}
catch (Exception e)
{
System.out.println("Error occurred!");
}
}
}