2017-06-01 51 views
1

所以,我有我的幻想二維字符陣列上,像這裏面的吧:如何檢查是否在一個二維數組中的所有行具有相同的大小

WWWSWWWW\n 
WWW_WWJW\n 
W___WWWW\n 
__WWWWWW\n 
W______W\n 
WWWWWWEW\n 

我需要編寫一個例外,當讀取它,它會檢查所有行是否具有相同的長度,如果不是,則返回一個自定義異常。

下面是一些什麼,我現在所擁有的

for (int i = 0; i < contalinhas; i++) { 
     for (int j = 0; j < linelenght; j++) { 
      System.out.print(linhaslidas[i].charAt(j)); 
      storelab[i][j] = linhaslidas[i].charAt(j); 
      String linha = linhaslidas[i].get 
      //builder.append(storelab[i][j]); 
      //builder.toString(); 
      //System.out.print(builder); 

      if (storelab[i][j] != ('S') && storelab[i][j] != ('W') && storelab[i][j] != ('_') && storelab[i][j] != ('E')) { 
       throw new MazeFileWrongChar(i,j); 

正如你所看到的,我已經有一個「如果」作爲另一個異常(基本上,限制什麼樣的角色被允許),所以我想做一些類似的事情,通過數組並計算每一行的長度。如果它檢測到至少一個尺寸差異,則會發生異常。

事情是,我不知道如何編寫它,因爲我使用的是數組而不是字符串,例如(不同的方法)。

任何幫助?

+0

看起來你已經有'linelength',你正在使用循環j。那麼,爲什麼不''如果(linhaslidas [i] .length!= linelength)拋出新的MazeSizeWrongException();' –

回答

0

你可以在數組的第一個指數運行和比較數組的大小:

int initialLen = storelab[0].length; 

// Iterate from index 1, as we already got 0 
for (int i = 1; i < contalinhas; i++) { 
    int currLen = storelab[i].length; 
    if (initialLen != currLen) { 
     throw new SomeException(); 
    } 
} 

編輯:
如果您使用的是Java 8,你可以使用流,以獲得略微更優雅的解決方案,儘管不那麼高性能:

long lenths = Arrays.stream(storelab).mapToInt(s -> s.length).distinct().count(); 
if (lengths != 1L) { 
    throw new SomeException(); 
} 
+1

謝謝,它的工作! – Vist4w

0

您可以使用下面的例子:

public class ExampleStrings { 

    public static void main(String[] args) { 
     String[] valid = {"aaa", "bbb", "ccc"}; 
     String[] invalid = {"aaa", "bbb", "1ccc"}; 

     // will pass with no exception 
     allTheSameLength(valid); 

     // will throw an exception with appropriate message 
     allTheSameLength(invalid); 
    } 

    private static void allTheSameLength(String[] arr) { 
     if (arr == null || arr.length == 0) { 
      return; // or false - depends on your business logic 
     } 

     // get length of first element 
     // it is safe to do because we have previously checked 
     // length of the array 
     int firstSize = arr[0].length(); 

     // we start iteration from 'second' element 
     // because we used 'first' as initial 
     for (int i = 1; i < arr.length; i++) { 
      if (arr[i].length() != firstSize) { 
       throw new IllegalArgumentException("String array elements have different sizes"); // or throw exception 
      } 
     } 

    } 

} 

通過null或空參數是安全的。

相關問題