Java Unable to return variables -
the code fine, when need take variables out of functions , put them public static void, says variable cannot found. know how solve issue?
import java.util.*; public class greetings { public static void main(string[] args) { system.out.println("greetings, " + string(s) + ". " + string(j) +"!" + " " + int(z) + " years old"); } public static string fnamegenerator(string s){ scanner scan1 = new scanner(system.in); system.out.println("please enter first name: "); string first = scan1.next(); s = first.substring(0,1).touppercase(); return s; } public static string lastname(string j){ scanner scan2 = new scanner(system.in); system.out.println("please enter last name: "); string second = scan2.next(); int x = second.length(); string y = second.substring(0, x).tolowercase(); j = y.substring(0,1).touppercase(); return j; } public static int age(int z){ scanner scan3 = new scanner(system.in); system.out.println("please enter year of birth: "); int third = scan3.nextint(); z = (2015 - third); return z; } }
you not calling of methods, how expect them return something?
two things remember:
just because wrote
return s
@ end of method, not mean can accesss
outside of method. there's called scopes in java, means variable exists on scope it's define in- in case - inside methods. if want exist outside - take returned value , it.declaring methods nothing until call them
so in order access these variables, need this:
public static void main(string[] args) { string s = fnamegenerator(); string j = lastname(); int z = age(); system.out.println("greetings, " + s + ". " + j +"!" +" " + z + " years old"); }
one more thing can see did there- don't need pass methods, not doing given values before re-setting them. make sure declare fields inside. example age method should like:
public static int age(){ scanner scan3 = new scanner(system.in); system.out.println("please enter year of birth: "); int third = scan3.nextint(); int z = (2015 - third); return z; }
Comments
Post a Comment