hi all,
i’m using the following code and i’m getting
exception in thread “main” java.lang.nullpointerexception at the line which is in bold.
import java.io.;
import java.util.;
public class CaesarCipherLab{
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
String letters="abcdefghijklmnopqrstuvwxyz";
System.out.print("Please enter key: ");
int key=scan.nextInt();//get key from user
String strLine=null;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("plaintext.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
InputStreamReader isr= new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream ("out.txt");
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
fos.write(strLine.getBytes());
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
String encrypted = Encrypt(strLine,key,letters);//here error
System.out.println("msg encrypted: " + encrypted);
String decrypted = Decrypt(encrypted,key,letters);
System.out.println("msg decrypted: " + decrypted);
//decrypt encrypted message and display it on screen
//--------------------------------------------------
}
public static String Encrypt(String str, int key, String letters){
String encrypted= "";
for(int pos=0;pos < str.length();++pos){ //here error
char c=str.charAt(pos);
if (c == ' '){
encrypted += c;
continue;
}
int ind=letters.indexOf(c);
int ncpos=(ind+key)%26;
encrypted += letters.charAt(ncpos);
}
return encrypted;
}
public static String Decrypt(String str, int key, String letters){
//write the body of this method
//----------------------------
String decrypted= "";
for(int pos=0;pos < str.length();++pos){
char c=str.charAt(pos);
if (c == ' '){
decrypted += c;
continue;
}
int ind=letters.indexOf(c);
int ncpos=(ind-key)%26;
if (ncpos<0){ // if index minus
ncpos=(ind+26-key)%26;
}
decrypted += letters.charAt(ncpos);
}
return decrypted;
}}
Exception in thread “main” java.lang.NullPointerException
at CaesarCipherLab.Encrypt(CaesarCipherLab.java:55)
at CaesarCipherLab.main(CaesarCipherLab.java:40)