尝试打印对象的值时出现null异常

时间:2014-03-20 11:21:00

标签: java io

所以我在这里记录厨师姓名,城市和价值,并将其存储在obj中并尝试将值存储到文件中。

Package yummy;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

class Chef
 {
   int value;
   String name;
   String city;   
 }

public class Yummy21 {    
 static Chef[] obj=new Chef[2];
 static Scanner input=new Scanner(System.in);    

public static void main(String args[])
{   
   Chef[] obj=init(); 
   //public static Chef init();
    PrintWriter     printer=createFile("C:\\Users\\Creative_Cimmons\\Documents\\content.docx");

    for(Chef exam : obj)
    {
      createOutput(printer,exam); 
    } 
}

public static Chef[] init()
{
   for(int i=0;i<2;i++)
   {
    obj[i]=new Chef();
    System.out.println("for the object "+i+" enter the name ");
    obj[i].name=input.next();
    System.out.println("for the object "+i+" enter the city ");
    obj[i].city=input.next();
    System.out.println("for the object "+i+" enter the value ");
    obj[i].value=input.nextInt();
   }
return obj;
}
 public static PrintWriter createFile(String a)
 { 
     try
     { 
         File location=new File(a);
         PrintWriter printer=new PrintWriter(new BufferedWriter(new         FileWriter(location)));
        return printer;
     }       
     catch(IOException e)
     {
         System.out.println("I/O exception occured");
     }  
     return null;
 }

public static void createOutput(PrintWriter print,Chef exam )
{
    String holder=exam.name+" "+exam.city+" "+exam.value;   
    print.println(holder);               
}               
}

当我尝试运行它时会在createoutput(打印机,考试)中显示异常。请帮忙

谢谢,

1 个答案:

答案 0 :(得分:0)

obj[i]为空。将其初始化为Chef实例。您刚刚创建了一个包含Chef类型对象的数组。但是,您实际上还没有创建Chef的任何实例。因此,在循环中创建一个Chef的新实例,稍后再分配它的字段

for(int i=0;i<2;i++)
{
    obj[i] = new Chef();
    System.out.println("for the object "+i+" enter the name ");
    obj[i].name=input.next();
    System.out.println("for the object "+i+" enter the city ");
    obj[i].city=input.next();
    System.out.println("for the object "+i+" enter the value ");
    obj[i].value=input.nextInt();
}

还将文件指针更改为写入.txt而不是.docx文件