class - What is causing the "Exception in thread "main" java.lang.NullPointerException" Error? -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
so in middle of project , supposedly code fine part keep getting errors anyway. i'm not sure original problem i'm sure it's changed @ point during changes. despite pointing the line problem, can't figure out problem(s) is/are. causing error?
exception in thread "main" java.lang.nullpointerexception @ cafe.setname(cafe.java:14) @ cubancafe.main(cubancafe.java:16) import java.util.scanner; public class cubancafe { public static void main(string[] args) { string statename; scanner scan = new scanner(system.in); system.out.print(" enter state: "); statename = scan.nextline(); cafe cafestate = new cafe(statename); cafestate.setname(); cafestate.settaxrate(); system.out.println(cafestate);; system.out.println(cafestate.gettaxrate()); } } public class cafe { private string state, name; private double taxrate; public cafe(string state){ state = state.touppercase( ); name = null; taxrate = 0; } public void setname(){ if(state.equals("md")) name = "parkville cuban cafe"; else if(state.equals("va")) name = "alexandria cuban cafe"; else name = null; } public void settaxrate(){ if (state.equals("md")) taxrate = .06; else if (state.equals("va")) taxrate = .04; else taxrate = 0; } public double gettaxrate(){ return taxrate; } public string tostring(){ return (name); } }
the problem here:
state = state.touppercase( );
the variable state shadowing field state. can solve adding "this":
this.state = state.touppercase( );
Comments
Post a Comment