Reputation: 11
this code is to be used to write the data inserted in to a file when the loop runs the second student dont get entered i dont know why this keeps getting stuck at the second student and i have been working on this for hours
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++;
}
}
}
Upvotes: 0
Views: 61
Reputation: 20741
Things to do
put ww.close(); outside the while loop
change c.nextLine(); to 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();
}
}
Upvotes: 0
Reputation: 15673
You close your FileWriter in each iteration of your while loop... what did you think would happen?
Upvotes: 3
Reputation: 5802
you close the writer in the loop, move the close statement outside of the loop
ww.close();
Upvotes: 1