java - Input variable created at Main is a different value to that created in Method -
i have created method gets input user. however, issue when attempt return value of method, continuously asks new number input. instead, want ask number once, return it.
for example: following code illustrates want achieve without method, including within method causes difficulties:
working code inside main:
public static void main(string[] args) { scanner input = new scanner(system.in); int age; system.out.print("enter age: "); age = input.nextint(); system.out.print("/nyou're " + age + " years of age."); }
however, when try within method, have difficulties:
code inside method:
public static int getage() { scanner input = new scanner(system.in); int number; number = input.nextint() return number; }
the issue is, whenever try print system.out.print(getage()); asks number each time. why first code allow me print age without asking new number, calling method print number causes issues , continues ask new number.
effectively, want call method, ask number input once, call method return number user has entered.
its not having code job, design. recommend below approach, features are:
- a utility class , generic method
promptuserinput
prompt user input, passing message - it return string object, convert other objects required.
- if want access other methods/classes, store instance variable, else use print or whatever plan.
you can handle scanner object close once done, , parent thread ready die, need change.
p.s.: intention not providing chunk of codes make think how design. so, may need change per requirement, scenarios , test.
code:
public class usertest { public static void main(string[] args) { user user = new user(); user.promptuserage(); user.printuserage(user.getuserage()); //do something. user.printuserage(user.getuserage()); user.promptuserage(); user.printuserage(user.getuserage()); } } public class user { private int userage = 0; public void promptuserage() { string userinput = apputils.promptuserinput("enter age: "); userage = new integer(userinput); } public int getuserage(){ return userage; } public void printuserage(int age){ system.out.print("\nyou're " + age + " years of age."); } } public class apputils { public static string promptuserinput(string message) { scanner input = new scanner(system.in); system.out.println(message); string userinput = input.next(); return userinput; } }
Comments
Post a Comment