2017-05-07 26 views
-2

我很感謝任何幫助解決我遇到的這個問題。在下面的代碼行27,我得到一個錯誤,該位置無法解析爲變量。 (BufferedReader br = Parse.parseLocation(location,key);) 初始化爲null在我的程序中不起作用(我沒有得到我想要的結果)並且我很難弄清楚如何解決這個問題。在哪裏以及如何正確申報? 爲了更加清晰,我還粘貼了下面的Parse文件。 在此先感謝。解決加密程序中的錯誤,當/ null不能使用時,在哪裏/如何聲明變量

import java.util.*; 
import java.io.*; 

public class Main { 


public static void main(String[] args){ 
    System.out.println("Enter Cipher Key:"); 
    Scanner s = new Scanner(System.in); 
    String key = s.nextLine(); 


    System.out.println("Enter a text file or URL to encrypt:"); 
    System.out.flush(); 
    Scanner r = new Scanner(System.in); 
    String filename = r.nextLine(); 
    File f = new File(filename); 

    r.close(); 
    s.close(); 

    try{ 
    Porta cipher = new Porta(key); 

    cipher.ensureCapacity((int)f.length());  
    FileWriter fw = new FileWriter("out.txt"); 
    BufferedReader br = Parse.parseLocation(location, key); 
    String line = null; 


     while((line = br.readLine()) != null){ 
      String encrypted = cipher.encrypt(line.toUpperCase()); 
      fw.write(encrypted + "\n"); 

     } 

     br.close(); 
     fw.flush(); 
     fw.close(); 
    }catch(Exception e){ 
     System.out.println("Yikes! Something nasty happened"); 
     e.printStackTrace(); 
    } 
} 

}

和上述解析文件,如下所示:

import java.io.*; 
import java.net.URL; 

public class Parse { 

private static BufferedReader br; 
private static final String FORM = "http://"; //Identify a URL header 
public static BufferedReader parseLocation(String location, String key) 
{  
    try{ 
     if(location.startsWith(FORM)){ 
      URL url = new URL(location);  
      br = new BufferedReader(new InputStreamReader(url.openStream())); 
      System.out.println("\nURL successfully read"); 
     } 

     else{ //If input is a file 
      File file = new File(location); //New instance of URL 
      if(file.exists()){ 
       br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); 
      } 
      System.out.println("\nFile successfully read"); 
     } 
    } 

    catch(IOException e) 
    { 
     e.printStackTrace(); //Prints the stack trace of the Exception to System.err. 
    } 

    return br; 
    } 

}

回答

0
BufferedReader br = Parse.parseLocation(location, key); 

這裏你逝去的location作爲參數,但location變量尚未宣佈。

在調用Parse.parseLocation(...)之前,您需要將其聲明爲全局變量或局部變量。像這樣的東西

String location = "http://http://stackoverflow.com"; 
BufferedReader br = Parse.parseLocation(location, key); 
相關問題