找不到打印机的符号

时间:2017-05-01 11:17:20

标签: java

import java.util.*; 
import java.io.*;
public class Events{



   File output = new File ("chinese.txt");


  static ArrayList <Event> events = new ArrayList <Event>();


  public static void main(String[]args){


      try{
         Scanner sc = new Scanner(new File("events.txt"));
         File output = new File("chinese.txt");
         PrintWriter printer = new PrintWriter(output);
         while(sc.hasNext()){        
               //String temp = sc.nextLine();
            //System.out.println(temp);

            int num = sc.nextInt();
            String desc = sc.nextLine();


            events.add(new Event(num,desc));


         }

         //break;   






      }
      catch(Exception e){

         System.out.println("Invalid file");


      }

      Collections.sort(events);

      for(int i = 0; i<events.size();i++){

         System.out.println(events.get(i));
         printer.println(events.get(i).toString()); 
      } 

 `}

}'

我创建了一个打印机对象和一个新的文件对象来打印一个arraylist的内容,但在我的for循环中它找不到符号,我已经尝试了一切来修复它而没有运气。

2 个答案:

答案 0 :(得分:0)

您需要在try块之前声明打印机,否则打印机的范围仅限于try块。这将解决它:

public static void main(String[]args){

  PrintWriter printer = null;
  try{
     Scanner sc = new Scanner(new File("events.txt"));
     File output = new File("chinese.txt");
     printer = new PrintWriter(output);
     while(sc.hasNext()){        
           //String temp = sc.nextLine();
        //System.out.println(temp);

        int num = sc.nextInt();
        String desc = sc.nextLine();


        events.add(new Event(num,desc));


     }

     //break;   






  }
  catch(Exception e){

     System.out.println("Invalid file");


  }

  Collections.sort(events);

  for(int i = 0; i<events.size();i++){

     System.out.println(events.get(i));
     printer.println(events.get(i).toString()); 
  } 

}

答案 1 :(得分:0)

在try块中声明了

printer,但是你试图在它之外使用它。在try块中包含for循环,它应该可以解决你的问题

import java.util.*; 
import java.io.*;
public class Events{



   File output = new File ("chinese.txt");


  static ArrayList <Event> events = new ArrayList <Event>();


  public static void main(String[]args){


      try{
         Scanner sc = new Scanner(new File("events.txt"));
         File output = new File("chinese.txt");
         PrintWriter printer = new PrintWriter(output);
         while(sc.hasNext()){        
               //String temp = sc.nextLine();
            //System.out.println(temp);

            int num = sc.nextInt();
            String desc = sc.nextLine();


            events.add(new Event(num,desc));


         }

         //break;   

          Collections.sort(events);

      for(int i = 0; i<events.size();i++){

         System.out.println(events.get(i));
         printer.println(events.get(i).toString()); 
      } 




      }
      catch(Exception e){

         System.out.println("Invalid file");


      }



 }

}