2

我的教授要求我们生成这个输出:

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;
            }
        }
    }

}
4

6 回答 6

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();
}
于 2012-11-01T16:32:49.433 回答
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();
  }
}
于 2012-11-01T16:37:03.723 回答
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

于 2012-11-01T16:30:02.333 回答
0

嗯,别难过。我会做你一开始做的同样的事情。但是,您可以只使用两个循环而不使用数组来执行此操作。

让一个循环简单地从 1 迭代到 26。然后让另一个循环从大写字母 A 的 ASCII 值 (65) 到大写字母 Z 的 ASCII 值 (90) 进行迭代。您现在需要做的就是将 ASCII 值转换为字符串,然后进行连接。

http://www.asciitable.com/

于 2012-11-01T16:29:58.420 回答
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) + " ");

    }
}

}

于 2012-11-01T16:30:09.993 回答
-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();
 }
}
于 2012-11-01T16:25:31.663 回答