有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要帮助/无法重载泛型方法

我需要重载GenericMethodtest的泛型方法printArray,以便

it takes two additional integer arguments, lowsubscript and highsubscript. A call to this method prints only the designated portion of the array. Validate lowsubscript and highsubscript. if either is out of range, the overloaded printarray method should throw an invalidsubscriptexception; otherwise, printArray should return the number of elements printed.

Then modify main to exercise both verisons of printArray on arrays integerArray, doubleArray and characterArray. Test all capabilities of both versions of printArray.

这就是我到目前为止所做的,我被卡住了,不知道从哪里开始

public class GenericMethodTest   
{     
  public static void main(String[] args)   
  {        
     // create arrays of Integer, Double and Character  
     Integer[] integerArray = {1, 2, 3, 4, 5, 6};   
     Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};   
     Character[] characterArray = {'H', 'E', 'L', 'L', 'O'}   
  
   
     System.out.printf("%nArray integerArray contains:%n");
     printArray(integerArray); // pass an Integer array 
     System.out.printf("%nArray doubleArray contains:%n");
     printArray(doubleArray); // pass a Double array
     System.out.printf("%nArray characterArray contains:%n");
     printArray(characterArray); // pass a Character array
   }    

   // generic method printArray       
   public static <T> void printArray(T[] inputArray)      
   {
     // display array elements  
     for (T element : inputArray)   
       System.out.printf("%s ", element);

     System.out.println();
   }
} // end class GenericMethodTest   

共 (1) 个答案

  1. # 1 楼答案

    公共类打印{

    public static void main(String[] args) {
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
        
        System.out.println( "Array integerArray contains:" );
        printArray( intArray ); 
        printArray( intArray , 0, 3); //1 2 3 4
        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); 
        printArray( doubleArray , 2, 4); //3.3 4.4 5.5 
        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray );
        printArray( charArray , 3, 8); //exception
        
    }
    
    private static <T> void printArray(T[] arr) {
        printArray(arr, 0, arr.length-1);
    
    }
    
    private static <T> void printArray(T[] arr, int low, int high) {
        if(low<0 || high>arr.length-1) {
            throw new InvalidSubscriptException("Illegal lowSubscribt or highSubscribt");
        }
        for(int i=low; i<high+1; i++) {
            System.out.printf("%s ", arr[i]);
        }
        System.out.println();
    }
    

    }