Reputation: 93
Scanner in=new Scanner(System.in);
while(true){
int X = in.nextInt();
System.out.println(X);
}
The above code can only read the numbers in the order i entered them. Eg: 1 2 3 4 These numbers will be read as 1 2 3 4
I want them to be read in a reverse order. I can't find any methods to do so.
Upvotes: 2
Views: 324
Reputation: 100279
You can do it "without any other variables" recursively:
public static void revNumbers(Scanner in) {
if(!in.hasNextInt())
return;
int X = in.nextInt();
revNumbers(in);
System.out.println(X);
}
public static void main(String[] args) {
revNumbers(new Scanner(System.in));
}
Upvotes: 6