循环不起作用

时间:2013-11-16 17:27:53

标签: java

此代码用于写入插入文件的数据 当循环运行时,第二个学生不进入,我不知道为什么 这种情况一直困扰着第二个学生,而且我已经在这个问题上工作了好几个小时

import java.util.Scanner;
import java.io.*;

class wonder
{
public static void main(String args[]) throws IOException
{
    Scanner c = new Scanner(System.in);

    FileWriter ww = new FileWriter("D:\\student details.txt");
    BufferedWriter o = new BufferedWriter(ww);

    int counter = 0 ;
    int stnum = 1;

    while(counter < 4)
    {
        String name = "";
        int marks = 0;

        System.out.print("Enter student " + stnum + " name : " );
        name = c.nextLine();

        System.out.print("Enter marks : ");
        marks = c.nextInt();

        ww.write(stnum + " " + name + " " + marks );
        ww.close();

        counter++;
        stnum++;

    }


}
}

3 个答案:

答案 0 :(得分:3)

你在while循环的每次迭代中关闭你的FileWriter ......你想到会发生什么?

答案 1 :(得分:1)

在循环中关闭writer,将close语句移到循环之外

ww.close();

答案 2 :(得分:0)

要做的事

ww.close(); 放在while循环之外 改变 c.nextLine();到 c.next();

import java.util.Scanner;
import java.io.*;
class wonder
{
public static void main(String args[]) throws IOException
{
    Scanner c = new Scanner(System.in);
    FileWriter ww = new FileWriter("D:\\student details.txt");
    BufferedWriter o = new BufferedWriter(ww);
    int counter = 0 ;
    int stnum = 1;
    while(counter < 4)
    {

        String name = "";
        int marks = 0;
        System.out.print("Enter student " + stnum + " name : " );
        name = c.next();

        System.out.print("Enter marks : ");
        marks = c.nextInt();

        ww.write(stnum + " " + name + " " + marks );

        counter++;
        stnum++;

    }
  ww.close();
}
}