Java 中字母的值

Values from letters in Java

我的 Java class 有一项作业需要在一个程序中编写多个方法。在大多数情况下,我了解所有内容,除了我想获得 2 个字母之间的值的地方。这是方向 "Create a method that is passed 2 letters, then prints all the values between the first letter and the second letter, inclusive. When the first letter passed comes after the second letter alphabetically, swap the values before printing. Call the method using any two UPPERCASE letters." 这是我目前所掌握的

public static void main(String[] args){
    char first = 'A';
    char last = 'Z'; 
    printLetters(first,last);
}//end main

public static void printLetters(char a, char z){
    char temp;
    if(a < b){
        temp = a;
        a = b;
        b = temp;
    }//end if
    while(a <= b)
        a++;
}//end printLetters

所以基本上我不知道我应该如何从字母中获取值,然后我将如何对其进行编码以便它执行我被要求做的事情,即打印 2 个字母之间的所有值。我是初学者,方法已经让我头晕目眩,但这让我完全摸不着头脑。

是的,你做对了,你只需要做

public static void printLetters(char a, char b){
    char temp;
    if(a > b){
        temp = a;
        a = b;
        b = temp;
    }//end if
     while(a <= b)
        System.out.print((char)a++);
}//end printLetters

这称为转换,因为当您在内部执行 'a++' 时,java 会添加字符 'a' 的 ASCII 值,这会产生整数值,因此您需要将其转换回去到字符形式

您的 printletters 方法采用参数 az,但内部代码使用 ab。您可以通过将 printletters 更改为:

来解决此问题
printLetters(char a, char b) {

你的想法基本上是正确的,除了一些小错误:

  1. 您调用了第二个参数 z 但一直引用 b
  2. 你检查 a < b 是否应该是 a > b
  3. 因为您只想打印两个字母之间的值,所以您的 while 循环应该使用 <,而不是 <=
  4. 而您实际上忘记打印信件了

所以:

public static void printLetters(char a, char b) { //1st comment
    char temp;
    if (a > b) { // 2nd comment
        temp = a;
        a = b;
        b = temp;
    }//end if
    while (a < b) { // 3rd comment
        a++;
        System.out.println(a); // 4th comment
    }
}//end printLetters