Java for循环不递增

时间:2017-06-03 15:08:00

标签: java for-loop increment

private static boolean isValid(String content, char delimiter, int count) {
    return count == content.chars().filter(c -> c == delimiter).count();
}

BufferedReader inputStream = null; String fileLine; int employeeCount = 1; String[] years = new String[2]; //Employee[] employees = new Employee[employeeCount + 1]; List<Employee> employees = new ArrayList<>(); File myFile = new File("src/project1/data.txt"); //System.out.println("Attempting to read from file in: "+ myFile.getCanonicalPath()); try { FileInputStream fstream = new FileInputStream(myFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String[] data = strLine.split(" "); //while ( int i < employees.length ) { for (int i=1; i < employees.size(); i++ ) { if (data[1].equals("Executive")) { employees.add( new Executive(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) ); } else if (data[1].equals("Salesman")) { employees.add( new Salesman(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) ); } else { employees.add( new Employee(data[0],data[1],data[2], Integer.parseInt(data[3])) ); } //System.out.println(employees[i].toString()); System.out.println(i +" " + employeeCount); employeeCount++; } } for (int y=1; y < employees.size(); y++ ) { System.out.println(employees.get(y).getName()); } //System.out.println(employees.toString()); } catch (IOException io) { System.out.println("File IO exception" + io.getMessage()); } 按预期递增,但EmployeeCount始终为1 - 我在这里缺少什么?使用while循环逐行读取textfile - for循环检查第二个数据是否与字符串匹配并在匹配时创建对象库。我在这里有道理吗?

1 个答案:

答案 0 :(得分:0)

for循环没有递增,因为在第一次迭代后条件为false:

for (int i=1; i < employees.length; i++ ) {

employees.length为2,因为employeeCount是此行的一个(我必须假设,因为代码不完整):

Employee[] employees = new Employee[employeeCount + 1];

这一行创建了一个数组,其中employeeCount + 1为2,因此有两个位置。当employeeCount递增时,大小会自动调整...

我建议使用List而不是数组,因为List会根据需要进行扩展:

List<Employee> employees = new ArrayList<>();
...
employees.add(new Employee(...));
相关问题