lundi 29 juin 2015

how to print null or zero for empty fields in the file

If while reading some fields are blank then how to print 0 for integer and null for string?what can I do??

Please help me with this. It is reading name,rollno,age,street,city and zip from file but if age or zip is empty I want to print 0 and if data type is string and field is empty we want to print null.

Can anyone help me with it.


public class PrintStudentsFromFile {

public static void main(String[] args) {

 List<Student> students= new PrintStudentsFromFile().populateData("path to text file");

 for (Student student : students) {
 * Reads Files and returns a List of Students
 * @param filename
 * @return 
public List<Student> populateData(String filename){
Scanner s = null;
String nameAndRollNumber="";
    try {
        s = new Scanner(new File(filename));

    } catch (FileNotFoundException e) {
    List<Student> list = new ArrayList<Student>();
    while (s.hasNext()) {
    nameAndRollNumber = s.nextLine();
    String[] nameAndRollNumbers = nameAndRollNumber.split("\\s+");
    String name = nameAndRollNumbers[0];
    String roll = nameAndRollNumbers[1];
    list.add(new Student(name, roll));
    return  list;

} /** * * Student Object , with name and Roll Number Params */ class Student{

String name;
String rollNumber;

public Student(String name, String rollNumber) { = name;
    this.rollNumber = rollNumber;

public String getName() {
    return name;

public void setName(String name) { = name;

public String getRollNumber() {
    return rollNumber;

public void setRollNumber(String rollNumber) {
    this.rollNumber = rollNumber;

public String toString() {
    return "Name :"+name+"- Roll Number : "+rollNumber;


one of friend has helped me with this. but i am not getting how to enter 0 or null for empty fields

Aucun commentaire:

Enregistrer un commentaire