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:

  1. just because wrote return s @ end of method, not mean can access s 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.

  2. 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

Popular posts from this blog

How to show in django cms breadcrumbs full path? -

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -