Reverse number _order_ from scanner input recursively

I had problems trying to solve a recursive task and were unsuccessful.

The purpose of the assignment is to call a function

reverseNumbers(new Scanner("11 23 31 49 56 611"))

and get a conclusion

"611 56 49 31 23 11"

but it is not allowed to use arrays, lists, strings, and the method should only declare one variable.

The code I wrote does not work. I get an error StackOverflowthat I understand why I get. This is due to the fact that the parameter scandoes not change, and for recursion it should work. However, I do not know how to change the input argument using the tools available in the utility Scanner.

public static String reverseNumbers(Scanner scan){
   if (!scan.hasNext()) {
      return "";
   }
   else {
      return reverseNumbers(scan)  + " " + scan.nextInt();
   }
}
+4
source share
1 answer

, , .

, Java . , reverseNumbers(scan) scan.nextInt().

, :

  • , scan.hasNext()
  • reverseNumbers
  • , scan.hasNext()
  • reverseNumbers
  • , scan.hasNext()
  • reverseNumbers
  • ...

scan.hasNext() :

int next = scan.nextInt();
return reverseNumbers(scan) + " " + next;

, hasNext() ( hasNextInt(), , String next = scan.next()), , , "" 't .

+5

Source: https://habr.com/ru/post/1684738/


All Articles