好的大家好,我是java编程的新手,我真的遇到阵列问题。我的程序应该读取.txt文件,每行包含3个数字(这是卡路里的问题,第一个数字表示早餐,第二个是午餐,第三个是晚餐)
所以我创建了一个Array.list(卡路里),因为它将读取长度未知的文件。到目前为止,它现在工作我把值放入一个数组,但我想将这个数组拆分为三个单维数组。早餐价值阵列,另一个用于午餐,最后一个用于晚餐。
我的问题是我无法弄清楚如何划分主阵列的长度,以便为我的其他3个不同阵列分配大小。 (我试过像array.length / 3这样的东西,但它给了我一个错误的IndexOutOfBounds)我知道它非常凌乱和一切:(但我几乎得不到这个,如果你能给我至少一个想法我会非常感激!
import java.util.*;
import java.util.ArrayList;
import java.io.*;
public class lab {
public static void main(String[] args) {
readData("ARRAYLAB1.txt"); //read file arraylab1.txt
}
static void readData(String filename) {
try {
List<Integer> calories = new ArrayList<Integer>();
// Defining an integer Array List
Scanner myfile = new Scanner(new FileReader("ARRAYLAB1.txt"));
// Reading file using Scanner
while (myfile.hasNext()) {
calories.add(myfile.nextInt()); // Read file content using a while loop
}
int[] array = new int[calories.size()]; //Pass the array list to an array
for(int i = 0; i < calories.size(); i++)
array[i] = calories.get(i);
int size = array.length / 3; //This didn't work
int[] breakfast = new int[size]; <--- index out of bounds error
int[] lunch = new int[size];
int[] dinner = new int[size];
//the rest just assigns each value to their respective array
int counter = 1;
int j = 0;
int k = 0;
int x = 0;
for (int i = 0; i < array.length; i++) {
if (counter == 1) {
breakfast[j] = array[i];
counter++;
j++;
continue;
}
if (counter == 2) {
lunch[k] = array[i];
counter++;
k++;
continue;
}
if (counter == 3) {
dinner[x] = array[i];
counter = 1;
x++;
continue;
}
}
myfile.close(); // close the file
} catch (Exception e) { // Defined it just in the case of error
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
size必须是int值。当你获得索引超出范围的异常时,只需在监视窗口中添加size变量,以验证你确实有一个整数值。更好地将大小值舍入为整数,因为当它不是3的倍数时,除以3将不会给出整数值。您也可以将它转换为整数。
如果你的长度值是3的倍数,你的代码应该可以正常工作。
答案 1 :(得分:1)
然后代码变为:
List<Integer> calories = new ArrayList<Integer>();
Scanner myfile = new Scanner(new FileReader("ARRAYLAB1.txt"));
while (myfile.hasNext()) {
calories.add(myfile.nextInt()); // Read file content using a while loop
}
List<Integer> breakfast = new ArrayList<Integer>();
List<Integer> lunch = new ArrayList<Integer>();
List<Integer> dinner = new ArrayList<Integer>();
//the rest just assigns each value to their respective array
int counter = 1;
for (int i = 0; i < calories.size(i); i++) {
if (counter == 1) {
breakfast.add(calories.get(i));
counter++;
continue;
}
if (counter == 2) {
lunch.add(calories.get(i));
counter++;
continue;
}
if (counter == 3) {
dinner.add(calories.get(i));
counter = 1;
continue;
}
}