2014-11-24 59 views
1

我無法返回數組的值,我知道我返回它錯了,但我不知道如何。請幫助。返回數組主體()

這些是操作的指令:

說明:代碼,對於3種 不同狗類型提示)稱爲dogTypes(的方法,存儲類型稱爲狗, 一個本地陣列並返回該數組的在main()中調用語句。一旦 main()獲取數組,它將使用for循環在如下所示的單獨行上打印數組 內容,其中9表示 數值,以便標籤讀取「Dog Type 1:」,然後「Dog類型2: 「等,從陣列中檢索每種狗類型。您可以使用for循環中的 循環控制變量生成9值。在名爲YourLastNameFirstInitialArraysV1.java的程序中保存 的代碼。 狗類型9:XXXXXXXXXXXXXXX狗類型9:XXXXXXXXXXXXXXX

import java.util.Scanner; 

    public class BarrazaMArrayV2 
    {//BEGIN BarrazaMLE52 

     private static Scanner input = new Scanner(System.in); 

     public static void main(String[] args) 
     { 
     String[] dog = dogType(); 

     System.out.printf("Dog Type 1: %S", dog[0]); 

     System.out.printf("Dog Type 2: %S", dog[1]); 

     System.out.printf("Dog Type 3: %S", dog[2]); 


     } 


     public static String[] dogType() 

     { 
     String[] dogType = new String[3]; 

     System.out.printf("Enter your dog type: "); 
     dogType[0] = input.nextLine(); 

     System.out.printf("Enter your dog type: "); 
     dogType[1] = input.nextLine(); 

     System.out.printf("Enter your dog type: "); 
     dogType[2] = input.nextLine(); 

     return dogType[3]; 

     } 
    } 
+1

只要使用'返回dogtype;'。當你說'return dogType [3];'你試圖返回一個字符串,在這種情況下,因爲數組中有3件事情而不存在,所以'4'將是第4個。 – csmckelvey 2014-11-24 03:25:00

回答

1

你只返回數組的第3個指數爲整個數組返回。 更改此:

return dogType[3]; 

return dogType; 

而且你的陣列是不是有第三個指標。如果您嘗試訪問第三個索引,您將獲得ArrayIndexOutOfBoundsException

1

你不返回返回dogType [3]。

您可以使用:

return dogType 
1

您在返回數組走錯了路。

return dogType [3];

它返回該索引但不是數組的元素。

擦除[3]

返回dogType;

1

我看到一些問題。

  1. 您的函數dogType()應該返回一個String的數組,但您只返回一個元素。
  2. 您正在返回的元素不存在。 dogType[]數組的索引爲0到2,沒有索引3。

同時解決通過改變

return dogType[3]; 

return dogType; 
1

您正在嘗試,而不是返回數組的字符串。它與返回類型不兼容,因爲返回類型是字符串數組。所以它給你編譯時間的錯誤。

所以返回dogType代替dogType[3]

dogType is array of string 

dogtype[3]is just a string of dogType array index 3 
+0

它不是'docType'它是'dogType'。 – Joe 2014-11-24 03:30:17

+0

@johny謝謝改變。 – NFE 2014-11-24 03:32:01

1

首先,我看到,你必須知道函數的返回類型,並且該功能dogType的返回類型( )是String [],所以你必須返回一個String數組。

return dogType[3];//return a String object not the String array. 

,所以你可以試試這個:

return dogType;//return a String array.