2012-11-01 34 views
2

我的教授要求我們產生這樣的輸出:Java中使用兩個循環

A1 B2 C3 D4 E5

F6 G7 H8 I9 J10

K11 L12 M13 N14 O15

P16 Q17 R18 S19 T20

U21 V22 W23 X24 Y25

Z26

我得到了正確的輸出,但他不會接受我的代碼;他說我必須不使用數組而僅使用2個循環。我想不出任何可以產生相同輸出的解決方案。我想知道是否有可能使相同的輸出只有2個循環?我這樣做了我的代碼,但我的教授說我必須修改它。

public class lettersAndNumbers { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     String[] abc = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", 
       "S", "T", "U", "V", "W", "X", "Y", "Z", }; 

     int i = 0; 
     while (i < abc.length) { 

      int j = 1; 
      while (j <= 26) { 

       int k = 1; 
       while (k <= 5) { 

        System.out.print(abc[i] + j + "\t"); 
        j++; 
        i++; 
         k++; 

        if (k == 6) { 
         System.out.println(); 
        } 

       } 
       k = 1; 
      } 
     } 
    } 

} 
+0

我想你的教授會很高興知道你已經做到了這一點如果。 – Egor

+6

+1您自己嘗試,而不只是要求我們爲您做這一切! –

+1

兩個循環?如果您知道模數運算符,則可以在一個循環中執行此操作... –

回答

-2

這現在應該做的:

String[] abc = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", 
      "S", "T", "U", "V", "W", "X", "Y", "Z", }; 

for(int i=0; i<abc.length; i++){ 
System.out.println(abc[i] + (i+1) + "\t"); 
if(i % 5 == 0){ 
    System.out.println(); 
} 
} 
0

好了,不心疼。我會先做同樣的事情。但是,您可以僅使用兩個循環而不使用數組。

有一個循環只是從1到26迭代。然後有另一個循環從大寫A(65)的ASCII值,通過大寫Z(90)的ASCII值迭代。您現在需要做的就是將ASCII值轉換爲一個字符串並進行連接。

http://www.asciitable.com/

2

這裏有一個辦法做到這一點在一個for循環:

// 'A' starts at 65 
int ascii_offset = 65; 

// Loop 26 times and print the alphabet 
for (int index = 1; index <= 26; index++) { 

    // Convert an ascii number to a char 
    char c = (char) (ascii_offset + index - 1); 

    // Print the char, the index, then a space 
    System.out.print("" + c + (index) + " "); 

    // After 5 sets of these, print a newline 
    if (index % 5 == 0) { 
     System.out.println("\n"); 
    } 
} 

進一步閱讀有關ASCII的和int到char轉換,這裏有一個相關的討論:Converting stream of int's to char's in java

0

任何問題在一個循環中完成?

public class AlphaOneLoop { 
public static void main(String[] args) { 
    for (int i = 65; i <= 90; i++) { 
     System.out.print(new String(Character.toChars(i)) + (i - 65 + 1) + " "); 

    } 
} 

}

+0

如果使用模運算符實現它,則在每打印五次後都會忘記換行符:p +1。 – keyser

5

您可以循環上字符實際上,這將使你的代碼更易讀,並避免使用你的信的數組:

int count = 1; 
for (char letter = 'A'; letter <= 'Z';) { 
    for (int i = 1; i <= 5; ++i, ++letter, ++count) { 
     System.out.print(letter); 
     System.out.print(count + "\t"); 
     if (letter == 'Z') 
      return; 
    } 
    System.out.println(); 
} 
+0

爲什麼'我<= 5'是循環中的條件?我沒有明白:\ –

+0

@JaGb先清楚你的循環概念。看來你還沒有用過循環。 – Mohsin

2

我的Java是真的很生疏,但我想這就是你要找的東西:

for(int i = 0; i < 26; i++) { 
    System.out.printf("%c%d ", 'A' + i, i + 1); 

    if (i % 5 == 0) { 
    System.out.println(); 
    } 
}