Hi All,
pl correct the prg.
Q. Write a java prg to accept RollNo, Name of a Student and store it in Student.txt.Accept n records and store it.
Following are the drawbacks of o/p produced 1. When we write rno i.e. int {roll no of stud} to the file "Student.txt" it does not write the int value
i/p
C:\j2sdk1.4.1_01\bin>java StudentInfo
Enter how many students
3
Student 1
Enter Roll no.:
1
Enter Name :
Geeta
Student 2
Enter Roll no.:
2
Enter Name :
Pinky
Student 3
Enter Roll no.:
3
Enter Name :
Shaily
o/p written to file "student.txt" is GeetaPinkyShaily
2) When we print the values in Student.txt then student roll no is displayed correctly loop used is
while((b=fin.read())!=-1)
{
System.out.print(b);
}
But as char c=(char) b; is not done it does not print the name
C:\j2sdk1.4.1_01\bin>java StudentInfo
Enter how many students
3
Student 1
Enter Roll no.:
1
Enter Name :
Geeta
Geeta
Student 2
Enter Roll no.:
2
Enter Name :
Pinky
Pinky
Student 3
Enter Roll no.:
3
Enter Name :
Shaily
Shaily
Contents of "Student.txt" are :
1711011011169728010511010712138310497105108121
C:\j2sdk1.4.1_01\bin>
or
vice versa
while((b=fin.read())!=-1)
{
char ch=(char) b;
System.out.print(ch);
}
prints the the names correctly but not roll no
Following is the code. Kindly make the necessary changes......................
import java.io.*;
class StudentInfo
{
int rno;
String name;
StudentInfo()
{
rno=0;
name="";
}
void getDetails() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Roll no.: ");
rno=Integer.parseInt(br.readLine());
System.out.println("Enter Name : ");
name=br.readLine();
}
public static void main(String[] args) throws IOException
{
FileOutputStream fout=null;
FileInputStream fin;
int n;
char space=' ';
try
{
//open Student.txt
try
{
fout=new FileOutputStream("Student.txt");
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file Student.txt");
System.exit(0);
}
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter how many students");
n=Integer.parseInt(br.readLine());
StudentInfo s[]=new StudentInfo[n];
for(int i=0;i<n;i++)
{
s[i]=new StudentInfo();
System.out.println("Student "+(i+1));
s[i].getDetails();
int rollno=s[i].rno;
fout.write(rollno);
char c[]=s[i].name.toCharArray();
for(int z=0;z<c.length;z++)
fout.write(c[z]);
}
fout.close();
System.out.println("Contents of \"Student.txt\" are : ");
fin=new FileInputStream("Student.txt");
int b;
while((b=fin.read())!=-1)
{
System.out.print(b);
}
fin.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
I guess if we can distinguish between the roll no and name we can solve this. In the o/p file I want o/p as rno name rno name rno name i.e. 1 Geeta 2 Pinky 3 Shaily
Then, how to insert it ?
if I declare as
char ch=' ';
fout.write(ch);
it writes 32
And even if
char ch=' ';
fout.write((int)ch);
it wites 32 to Student.txt