java - Better explanation of unreachable code and getting value of int to another class -
please bare me new coder, started out. i've searched similar posts on matter , there lot, please understand don't. appreciate if explain little better, simpler.
i trying write first program. first part of program reverse number entered user, , don't have problem this. problem when try reversed number class
here code:
package secretidpack; import java.util.scanner; public class rennum { int reverse = 0; int storenumber; public int revmethod(){ scanner in = new scanner(system.in); storenumber = in.nextint(); while(storenumber != 0) { reverse = reverse * 10; reverse = reverse + storenumber%10; storenumber = storenumber/10; } return reverse; system.out.println(reverse); } }
the system.out.println part can confirm above code working properly, long keep return part out of code. put return part in, message there unreachable code @ system.out.println
now see being done here, make sure understand. need value of reversed number in class worked on further adding value multiplying etc. let's number entered 1234 , when revmethod part 4321, need number in class
package secretidpack; public class newsecretid { public static void main(string[] args){ rennum revobject = new rennum(); revobject.revmethod(); system.out.println(reverse); } }
now in class error "reverse" cannot resolved variable, why isn't class pulling "reverse" value previous class?
thanks!
as first question, have return
statement followed print statement. in case, problem when return
keyword found, execution flow exit method. thus, follows never executed.
to fix this, need invert order of return
, print
statement such printing take place before returning.
as per second question, reverse
string not exist within main
method. exists in other method calling, never declared in newsecretid
class, why getting error.
variables declared within methods not available outside declaring method. same applies class lever variables, since not available outside class. clear, can access them, not in way doing it.
to solve second issue, int reverse = revobject.revmethod()
. place whatever revmethod
gives integer variable called reverse
. sake of completeness can rename reverse
like. int foo = revobject.revmethod()
work.
Comments
Post a Comment