这个程序在哪里错了?

时间:2013-10-06 16:37:07

标签: java

这个程序反转了数组。现在,我如何创建一个函数来打印反转数组?

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

    }

}

3 个答案:

答案 0 :(得分:1)

您可以尝试使用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);
}
}

答案 1 :(得分:0)

您的反向函数返回char,但您希望它返回一个数组。以下是您需要做的事情:

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

答案 2 :(得分:0)

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

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