sanal
sanal

Reputation: 93

Read last input first, when reading through scanner

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

Answers (1)

Tagir Valeev
Tagir Valeev

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

Related Questions