2013-10-06 3 views
-2

ce programme inverse le tableau. maintenant, comment pourrais-je créer une fonction pour imprimer le tableau inversé?Où est-ce que je me trompe dans ce programme?

public class Question1 { 

    public static void main(String [] args) { 
     char[] myName = { 'H', 'A', 'S', 'H', 'I', 'M' }; 

     reverse(myName); 

    } 

    public static void reverse(char[] array) { 
     for (int i = 5; i >= 0; i--) { 
      char reverseArray = array[i]; 
     } 

    } 

} 
+0

Ce code compile? .. votre fonction inverse ne sélectionne que le premier élément, et retourne une variable non existante !. Vérifiez ce code http://ideone.com/ZdsAVg –

+0

@ AVolpe Je l'ai compris. Merci pour l'aide –

Répondre

1

Vous pouvez essayer d'utiliser la méthode charAt:

class ReverseString 
{ 
    public static void main(String args[]) 
    { 
    String original, reverse = ""; 
    Scanner in = new Scanner(System.in); 

    System.out.println("Enter a string to reverse"); 
    original = in.nextLine(); 

    int length = original.length(); 

    for (int i = length - 1 ; i >= 0 ; i--) 
    reverse = reverse + original.charAt(i); 

    System.out.println("Reverse of entered string is: "+reverse); 
} 
} 
0

Votre fonction inverse renvoie une char, mais vous le voulez retourner un tableau. Voici ce que vous devez faire:

public class Question1 { 
    public static void main(String [] args) { 
     char[] myName = { 'H', 'A', 'S', 'H', 'I', 'M' }; 

     char[] temp = reverse(myName); // this should be an array 
     print(temp); 
    } 

    public static char[] reverse(char[] array) { 
     char[] reverse = new char[5]; // define an array here 
     for (int i = 5; i >= 0; i--) { 
      reverse[5 - i] = array[i]; 
     } 
     return reverse; 
    } 

    public static void print(char[] array) { // the parameter should be an array 
     System.out.println(array); 
    } 
} 
0

public static void main (String [] args) { omble myName [] = { 'H', 'A', 'S', 'H', ' JE SUIS' };

char temp[] = reverse(myName); 
    print(temp); 
} 

public static char[] reverse(char array[]) { 
    char reverse []= new char[6]; 
    for (int i = 5; i >= 0; i--) {//Watch out the length of array. 
     reverse[5 - i] = array[i]; 
    } 
    return reverse; 
} 

public static void print(char array[]) { 
    System.out.println(array); 
} 
Questions connexes