recursion - Reverse order of number in scanner object returning a string (java) -
i have major head wrecker of assignment , lost of how go @ it. assignment follows:
write recursive method in java public static string reverse(scanner scan), scanner object contains numbers , numbers supposed returned in reverse order string. , here's tricky part, you're not allowed use arrays, lists or string it's suppose declare 1 single variable.
the input of reverse(new scanner("20 33 40") example should return: " 40 33 20".
i know how go @ if wasn't because of restraints. don't know how suppose solve this. i'm pretty new @ programming , know of against helping out assignments, appreciate pointers.
first possibility use string
you can use directly string
data structure. adding at beginning instead of @ end when read new number.
basically code like:
string str = ""; while (yourcondition) { str = scanner.nextint() + " " + str; } return str;
second possibility use stringbuffer or stringbuilder
stringbuilder str = new stringbuilder(); while (yourcondition) { str.insert(0, " ").insert(0, scanner.nextint()); } return str.tostring();
third possibility use recursion:
public string read(string str, scanner scanner) { if (testexitcondition) { return str; } return scanner.nextint() + " " + str; } // called system.out.println(read("", scanner));
note
the first solution use string creating many instances of string, having 1 reference it.
the second solution use existing classes internally uses arrays operate on strings.
the third leave jvm reference created string, no explicit reference string present in code. don't have explicit variable declarations (only in signature of method, not outside).
Comments
Post a Comment