while 循环不递增 java

While loop not incrementing java

我才刚刚开始了解 java。我的 while 循环似乎没有增加。这是我在 try and catch 中的 while 循环的片段:

File file = new File("Reservation.txt");
Scanner sc = new Scanner(file);

    sc.useDelimiter(",");
try {
    while (sc.hasNext()) {
        i = 0;

        newRes[i] = readRec;

        fuN2 = sc.next();
        newRes[i].fullName = fuN2;
        readRec.setFirstName(fuN2);
        System.out.println("\n" + newRes[i].fullName);

        cn2 = sc.next();
        newRes[i].contact = cn2;
        readRec.setContact(cn2);
        System.out.println(newRes[i].contact);

        dt2 = sc.next();
        newRes[i].date = dt2;
        readRec.setDate(dt2);
        System.out.println(newRes[i].date);

        pa2 = sc.nextInt();
        newRes[i].pax = pa2;
        readRec.setPax(pa2);
        System.out.println(newRes[i].pax);

        bt2 = sc.next();
        newRes[i].bday = bt2;
        readRec.setBirthday(bt2);
        System.out.println(newRes[i].bday);

        ch2 = sc.nextInt();
        newRes[i].child = ch2;
        readRec.setChild(ch2);
        System.out.println(newRes[i].child);

        se2 = sc.nextInt();
        newRes[i].senior = se2;
        readRec.setSenior(se2);
        System.out.println(newRes[i].senior);

        pr2 = sc.nextInt();
        newRes[i].j = pr2;
        readRec.setPrice(pr2);
        System.out.println(newRes[i].j);

        dpr2 = sc.nextInt();
        newRes[i].k = dpr2;
        readRec.setDisPrice(dpr2);
        System.out.println(newRes[i].k);
        sc.next();
        sc.nextLine();
        i++;
    }

} catch (NoSuchElementException e)
{
    sc.close();
    System.out.println("===============================");

}

每当我尝试打印出变量 'i' 时,它总是打印出 0,但它总是正确且按顺序读取文件。

更新:我从 while 循环中删除了 i 声明,答案应该在下面。

您在循环中做的第一件事是将i设置为0 …

所以 i 在循环结束时递增,但在下一个循环时恢复。

但是当打印 i 时,在循环执行后打印时,你应该总是得到 1,而不是 0。

试试这个:

var i = 0;
File file = new File( "Reservation.txt" );
Scanner sc = new Scanner( file );

sc.useDelimiter(",");
try 
{
  while (sc.hasNext()) 
  {
    // i = 0; Get rid of this line!!!

    newRes [i] = readRec;

    fuN2 = sc.next();
    newRes [i].fullName = fuN2;

    …

    dpr2 = sc.nextInt();
    newRes [i].k = dpr2;
    readRec.setDisPrice( dpr2 );
    System.out.println( newRes [i].k );
    sc.next();
    sc.nextLine();
    ++i;
  }
} 
catch( NoSuchElementException e )
{
  sc.close();
  System.out.println("===============================");
}