我的教授让我们生成这个输出:
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个循环的情况下这样做。我想不出有什么解决方案能产生相同的输出。我想知道是否有可能只使用两个循环就可以实现相同的输出?我做了这样的代码,但我的教授说我必须修改它。
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;
}
}
}
}
发布于 2012-11-01 16:32:49
实际上,您可以在chars上循环,这将使您的代码更加可读性,并避免为您的字母使用数组:
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-01 16:30:02
这里有一种方法可以在一个循环中完成:
// '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-01 16:37:03
我的Java非常生疏,但我认为这正是您要寻找的:
for(int i = 0; i < 26; i++) {
System.out.printf("%c%d ", 'A' + i, i + 1);
if (i % 5 == 0) {
System.out.println();
}
}
https://stackoverflow.com/questions/13181286
复制相似问题