0
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!

4

2 に答える 2

3

printeaza(c, scan)(made from )への最初の呼び出しもpublic static void maina でラップする必要がありSystem.out.println(..)ます。

このような:

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;
        }
    }
}

Cruncher のアドバイスを取り入れると、次のように書きます。

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;
    }
}
于 2013-11-01T13:35:22.910 に答える
2

問題は、への呼び出しがprinteaza独自の文字を出力せず、再帰呼び出しの文字のみを出力することです。

つまり、printeaza(c, scan);inを次のmainように変更する必要があります。System.out.println(printeaza(c, scan);

また、このようにユーザー入力に再帰呼び出しを使用することは、正直言ってあまり良い考えではないことを指摘したいと思います。:/

于 2013-11-01T13:35:31.100 に答える