Nullpointer exception when modifying string through another class - Java -
in main method, doing this:
rtalgorithm rt = new rtalgorithm(); string s = "looooolasdasdl"; rt.encrypt(s); system.out.println(s);
here rt class:
package rt.encrypt; public class rtalgorithm { public static string encrypt(string s) { alg_flip(s); return s; } private static string alg_flip(string s) { string s1 = ""; for(int = s.length() - 1; >= 0; i++) { s1 = s1 + s.charat(i); } return s1; } }
however, giving me nullpointerexception on rt.encrypt(s) line in main method have
if return value in method in .modify have value back:
you're doing:
string s = "looooolasdasdl"; rt.modify(s); system.out.println(s);
you need
string s = "looooolasdasdl"; string s2 = rt.modify(s); system.out.println(s2);
and in modify method need return of alg_flip() call
public string modify(string s) { return alg_flip(s); }
edit
if use lot of algorithms should consider strategy pattern
the main problem of attempt still call method parameter, don't save happend return statements.
edit 2:
i got main problem, although return part problem:
for(int = s.length() - 1; >= 0; i++) { s1 = s1 + s.charat(i); }
you want chars @ , loop reverse add variable
for(int = s.length() - 1; >= 0; i--) { s1 = s1 + s.charat(i); }
this should do
this works me:
public class main { public static void main(string[] args) throws parseexception { rtalgorithm rta = new rtalgorithm(); string s = "looooolasdasdl"; s = rta.encrypt(s); system.out.println(s); } } class rtalgorithm { public static string encrypt(string s) { return alg_flip(s); } private static string alg_flip(string s) { string s1 = ""; (int = s.length() - 1; >= 0; i--) { s1 = s1 + s.charat(i); } return s1; } }
but if write static methods, don't need create instance.
instead of rt.encrypt(s);
rtalgorithm.encrypt(s);
Comments
Post a Comment