我正在做一個加密項目,我大部分都在工作。我正在從文件中讀取明文,並對其進行加密,然後將其寫入另一個文本文件。我有解密相同的東西。我有這個工作,但我有點困惑與讀取和寫入文件的嘗試和捕獲方法。我有兩種嘗試和捕獲方法,第二種嘗試方法不能識別我的「解密」變量。我應該如何處理這個問題?這裏是我的代碼:如何讓Java識別try塊內聲明的變量?
public static void decrypt(String pathname)
{
File file = new File(pathname);
Scanner input = null;
try
{
input = new Scanner(file);
String tempEncrypted = input.nextLine();
StringBuffer encrypted = new StringBuffer(tempEncrypted);
StringBuffer decrypted = new StringBuffer("");
int shiftAmount = (int)encrypted.charAt(0);
for(int i = 1; i < encrypted.length(); i++)
{
int decChar = ((int)encrypted.charAt(i) - shiftAmount);
while((int)decChar < 32)
{
decChar+=95;
}
decrypted.append((char)decChar);
}
}
catch(FileNotFoundException ex)
{
System.out.println("*** Cannot open " + pathname + " ***");
System.exit(1);
}
try {
BufferedWriter out = new BufferedWriter(new FileWriter("decrypted.txt"));
for(int j = 0; j < decrypted.length(); j++)
{
out.write(decrypted.charAt(j));
}
out.close();
}
catch (IOException e) {}
}
謝謝和任何幫助,將不勝感激。
我該如何解決這個問題呢?可以嘗試參數? – masonc15
將變量聲明移至適當的範圍。 (「範圍」表示括住括號)。 –
此外,它是一個try *塊*,而不是「嘗試方法」。 –