我在这个程序上碰壁了

public class Assignment11 {


public int sumConstants ()
{
   char ch = 'A';

   for (int i = 0 ; i<=90 && i >= 65 ; i++)
   {
         if (Character.isUpperCase(ch))
    {
         int x = (int) ch;

    }
   }

    return ch;
}
public static void main(String[] args) {

    Scanner in = new Scanner ( System.in );

    Assignment11 a11 = new Assignment11();

    int x = a11.sumConstants();

    System.out.println("Enter TWO upper case Characters:");

    String s = in.nextLine();

    System.out.println("The sum of the constants is: " + x);


}

}


这是我最终得到的输出

Enter TWO upper case Characters:
AE
The sum of the constants is: 65


我想要的输出示例是:

Enter TWO upper case Characters:
IO
The sum of the constants is: 380


因此,基本上发生的是将“ JKLMN”的ASCII值加在一起。

最佳答案

在您的方法中添加2个参数,并将2个字符传递给该方法:

public static int sumConsonants(char start, char end){
    int sum = 0;
    for(int x=start+1; x<end; x++){
        if(!Character.toString((char)x).matches("[aeiouAeiou]+"))  //if is consonant
            sum += x;                                              //add to sum
    }
    return sum;
}


完成运行:

Scanner scn = new Scanner(System.in);
char start = scn.nextLine().charAt(0);
char end = scn.nextLine().charAt(0);
System.out.println("The sum of the constants is: " + sumConsonants(start, end));




测试:

System.out.pritln(sumConsonants('A', 'E'));  //66 + 67 + 68


输出:

201

07-26 09:05