Reputation: 327
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
char c = 0;
Scanner scan = new Scanner(System.in);
printeaza(c, scan);
}
public static char printeaza(char c, Scanner sc) {
c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(c, sc));
return c;
} else {
return c;
}
}
}
What i'm trying to do is type letters from the keyboard and then have them diplayed in reverse. I know it can be made very easy with a for loop and char arrays but i'm curious about making it recursively and using only one char variable. I almost made it but it seems it prints all but the first letter.
So if I type: "a s d f" instead of "f d s a" i get only "f d s". I think I know why, it's because the Println statement it's only inside the if statement but I kind of run of ideeas about how to make the function "catch" the first letter as well. I hope you can have a look, thanks!
Upvotes: 0
Views: 1406
Reputation: 4078
Your first call to printeaza(c, scan)
(made from public static void main
) needs to be wrapped with a System.out.println(..)
as well.
Like this:
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
char c = 0;
Scanner scan = new Scanner(System.in);
System.out.println(printeaza(c, sc)); // <-- changed line
}
public static char printeaza(char c, Scanner sc) {
c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(c, sc));
return c;
} else {
return c;
}
}
}
Incorporating Cruncher's advise, I'd write it like this:
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(printeaza(sc));
}
public static char printeaza(Scanner sc) {
char c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(sc));
}
return c;
}
}
Upvotes: 3
Reputation: 8171
The problem is that a call to printeaza
doesn't print its own character, only that of it's recursive call.
In other words, printeaza(c, scan);
in main
needs to be changed to System.out.println(printeaza(c, scan);
Also, I would just like to point out that using recursive calls for user input like this is not a very good idea to be honest. :/
Upvotes: 2