2011-11-03 28 views
1

我正在做一個戰艦遊戲在控制檯中玩 - 你如何NSLog字符串,使他們看起來像一個10×10的網格,而不是一長串。每個座標是來自boardArray的@「X」對象。 理想情況下,我想在循環中做 - 但是,無論如何! 謝謝。如何打印出一個10 x 10的對象網格到控制檯

NSMutableArray *boardArray = [[NSMutableArray alloc]initWithCapacity:110]; 
NSMutableString *blank =[[NSMutableString alloc]initWithString:@"X"]; 

for (int x = 0; x < 101; x++) { 
    [boardArray insertObject:blank atIndex:x]; 
} 


for (int x = 0; x < 100; x++){ 

    // what goes here to print (NSLog) a 10 x 10 grid of objects 
    // each object is a string @"X" from the boardArray. 

} 

回答

3

簡單的例子:

// Create Array (01, 02, 03, 04, 05, etc.) 

NSMutableArray *theArray = [[NSMutableArray alloc]init]; 
for (int i = 0; i < 100; i++) { 
    [theArray addObject:[NSString stringWithFormat:@"%02d",i]]; 
} 

// Print Array 

for (int i = 0; i < 10; i++) { 
    NSArray *subArray = [theArray subarrayWithRange:NSMakeRange(0+(i*10),10)]; 
    NSLog(@"%@",[subArray componentsJoinedByString:@" "]); 
} 

輸出:

00 01 02 03 04 05 06 07 08 09 
10 11 12 13 14 15 16 17 18 19 
20 21 22 23 24 25 26 27 28 29 
30 31 32 33 34 35 36 37 38 39 
40 41 42 43 44 45 46 47 48 49 
50 51 52 53 54 55 56 57 58 59 
60 61 62 63 64 65 66 67 68 69 
70 71 72 73 74 75 76 77 78 79 
80 81 82 83 84 85 86 87 88 89 
90 91 92 93 94 95 96 97 98 99 
+0

謝謝安妮 - 完美的答案 – pete

0

你需要看的NSMutableString類來構建你的字符串,然後在您的NSLog()顯示

0

你可以用C的printf()這工作就像NSLog的,但不打印實際的日誌信息(時間等信息),並且不會自動把新行(你仍然可以使用\n

+0

謝謝大家的所有答案 - 他們都很好,但最適合我的是安妮。 – pete

1

讓我的模型更符合您的結構,例如因此10×10是二維結構。

NSMutableArray *board = [[NSMutableArray alloc] initWithCapacity:10]; 
    NSMutableArray *row = [[NSMutableArray alloc] initWithCapacity:10]; 

    for (int i = 0; i < 10; i++) { 
    [row addObject:@"X"]; 
    } 

    [board addObject:row]; 

    NSMutableArray *preFilledRow = nil; 

    for (int i = 0; i < 9; i++) { 
    preFilledRow = [row mutableCopy]; 
    [board addObject:preFilledRow]; 
    [preFilledRow release]; preFilledRow = nil; 
    } 

    [row release]; row = nil; 

    for (NSMutableArray *boardRow in board) { 
    NSLog(@"%@", [boardRow componentsJoinedByString:@" "]); 
    // printf("%s\n", [[boardRow componentsJoinedByString:@" "] UTF8String]); <- Use this if you don't want additional info printed 
    } 

    [board release]; board = nil; 
相關問題