![](/img/trans.png)
[英]Is there a way to change the filename I am calling, so that I don't need all these if/else statements?
[英]Is there a way to do this so I don't have 64 if statements?
我被告知從一個 txt 文件創建一個二維數組,該文件有“carModel,carColor”,后跟一個新行。 二維數組是 8x8,每次出現某個 carmore 和 carcolor 時,它們各自的 [x][y] 坐標表示它們的計數都會增加 1。
到目前為止,我已經閱讀了該文件,從該文件創建了一個二維數組,並創建了一個 output,其中二維數組和每個插槽都填充了零,但我似乎想出的唯一方法是更新每個 model,顏色計數是如果我手動制作 64 個 if 語句來檢查它們是否出現在列表中 n+ 次。 當然必須有另一種方式?
例如,當我的掃描儀讀取列表時,我需要它來檢查列表是否重復汽車型號、汽車顏色,如果是,則更新該汽車制造商和顏色的計數。
這是我到目前為止的代碼:
public static void main (String [] args) throws Exception
{
String [][] cars = new String [8][8];
ArrayList <String> colors = new ArrayList<>();
colors.add("BLUE ");
colors.add("BLACK ");
colors.add("BROWN ");
colors.add("GREEN ");
colors.add("RED ");
colors.add("SILVER");
colors.add("WHITE ");
Collections.sort(colors);
ArrayList <String> models = new ArrayList<>();
models.add("Escape ");
models.add("Explorer");
models.add("F150 ");
models.add("F250 ");
models.add("Flex ");
models.add("Mustang ");
models.add("Taurus ");
Collections.sort(models);
cars [0][0] = "_____ ";
for (int a = 1; a < cars.length; a++)
{
cars[0][a] = (models.get(a-1)) + " ";
}
for (int b = 1; b < cars.length; b++)
{
cars[b][0] = (colors.get(b-1)) + " ";
}
for (int fir = 1; fir < cars.length; fir++)
{
for (int sec = 1; sec < cars[1].length; sec++)
{
if (cars[fir][sec] == null)
{
cars[fir][sec] = "0 ";
}
}
}
for (int first = 0; first < cars.length; first++)
{
for (int second = 0; second < cars[first].length; second++)
{
System.out.print(cars[first][second]);
}
System.out.println();
}
File file = new File ("C:\\Users\\delta\\Documents\\NetBeansProjects\\SchoolWork\\cars.txt");
Scanner sc = new Scanner(file);
String ab = sc.nextLine();
while (ab != null)
{
String [] nums = sc.nextLine().split(" ");
for (int i = 0; i < nums.length;i++)
{
System.out.println(nums[i]);
}
}
}
您需要做的是使用ArrayList.indexOf()
方法。
然后使用這些設置或增加 8x8 數組中的條目。 每次您閱讀汽車的顏色和 model。
int[][] count = new int[][];
while (reading in data) {
get color
get model
int row = modelList.indexOf(model)
int col = colorList.indexOf(color)
count[row][col]++
}
我還建議您修剪顏色和 model 周圍的空白區域。 只要您使用System.out.printf()
,它就會使調試變得困難並且您不需要它來格式化 output 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.