2011-01-08 1 views
0

Je suis très mauvais récursion ...Comment retourner une chaîne de char [] tableau en utilisant la boucle récursive (java)

Je dois convertir un tableau char[], en utilisant uniquement récursion, dans une chaîne -. Sans en utilisant les boucles for(), while() etc. Par exemple, si j'ai un tableau de caractères:

a[0]='H', a[1]='e', a[2]='l',a[3]= 'l',a[4]= 'o' 

il retourne H e l l o.

Qu'est-ce que je fais mal?

public String toFormattedString(char[] a) 
{ 
     int temp =a.length; 
     if (a == null) 
     return "null"; 
     if (a.length == 0) 
     return "0"; 
     if(a.length == 1) 
      else if(a[0] == a[a.length]) 
     return toFormattedString (a[a.length -1])+a[a.length]; 
+0

Le compilateur ne montre aucune erreur? –

+0

Il est. Mais cela ne m'aide pas à comprendre la racine du problème. :( – Daniel

+1

Vous êtes également assez lit à l'orthographe :-) – paxdiablo

Répondre

1

En récursivité, une méthode s'appelle elle-même avec des données modifiées de l'appel d'origine. Ceci est fait jusqu'à ce qu'un cas de base soit atteint, dans lequel il n'est plus possible de modifier les données.

Dans votre cas, le cas de base est lorsque le tableau de caractères est composé d'un seul élément. Ce char sera la chaîne. Sinon c'est le premier élément avec le reste ajouté dans un appel récursif. La chaîne "Hello" est 'H' avec toFormattedString({'e','l','l','o'}) en annexe. Donc, si votre tableau char contient seulement un élément (length==1) il suffit de retourner cet élément en tant que valeur de chaîne.

Sinon, prenez le premier élément et allez récursivement vers le tableau char restants sans le premier élément. Récursive jusqu'à ce qu'il ne reste plus qu'un élément.

public static String toFormattedString(char[] a) 
{ 
    if (a.length==1) return String.valueOf(a[0]); 
    else  
    return a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length)) ; 

} 

Vous pouvez même mettre le corps de la méthode dans une ligne illisible (non recommandé, je l'ai mentionné juste pour le plaisir):

return((a.length==1)?String.valueOf(a[0]):a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length))); 

MISE À JOUR: Un switch -Déclaration donne un code lisible dans ce exemple:

public static String toFormattedString(char[] a) 
{ 
    switch (a.length) 
     {case 0 : return "";  
     case 1 : return String.valueOf(a[0]); 
     default: return a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length)); 
     } 
} 

Utilisation:

public static void main (String[] args) throws java.lang.Exception 
{ 
    System.out.println(toFormattedString("Hello".toCharArray())); 
} 
1

Pourquoi doint cette façon si vous avez new String(char[])

En utilisant récursion,

Je vous suggère fortement que vous compreniez recursion et ce code bien avant de soumettre votre HW.

package org.life.java.so.questions; 

/** 
* 
* @author Jigar 
*/ 
public class StringCharRec { 

    public static String toStringFromCharArr(String str, char[] arr, int pos) { 
     if (pos == arr.length) { 

      return str; 
     } 
     str += Character.toString(arr[pos]); 
     return toStringFromCharArr(str, arr, ++pos); 


    } 

    public static void main(String[] args) { 
     char[] ar = {'a', 'b', 'c'}; 
     System.out.println(toStringFromCharArr(new String(), ar, 0)); 
    } 
} 
+0

C'est ce que veut mon prof. La méthode doit commencer par public String toFormattedString (char [] a) { – Daniel

+0

Vérifier la mise à jour ......... –

0

Chaîne toFormattedString publique (char ch []) { si (ch.length < = 0) return ""; retour ch [0] + (toFormattedString (new String (ch) .Substring (1) .toCharArray ()));}

+1

J'aime l'utilisation de new String (char []) pour faire ce que la fonction est supposée faire faire. ;) –

0

Encore une autre réponse.

public String toFormattedString(char[] a) { 
    return a == null ? "null" : toFormattedString(a, 0); 
} 

private String toFormattedString(char[] a, int pos) { 
    return pos >= a.length ? "" : a[pos] + toFormattedString(a, pos+1); 
} 

Ceci divise la chaîne en deux à chaque fois. Cela ne va pas exploser sur de longues chaînes. (Faire un caractère à la fois pourrait un StackOverflowError de cas;)

public String toFormattedString(char[] a) { 
    return a == null ? "null" : toFormattedString(a, 0, a.length); 
} 

private String toFormattedString(char[] a, int start, int end) { 
    int len = end-start; 
    return len==0?"":len==1?""+a[start]: 
    toFormattedString(a,start,start+len/2)+toFormattedString(a,start+len/2,end); 
} 

Je ne vois pas comment cela est une chaîne « formatée ».Il n'y a pas de formatage, c'est juste une chaîne.

Questions connexes