0

This is my first question on this site so I'm not sure how to do this, but my question is as follows: This is just a small piece of a code with multiple methods. I need to print the ASCII codes of all the characters in a String (input from the user). Now I am trying to use a for-loop which scans the first character prints the ASCII code of it, then scans the next one etc. But at the moment its just printing the first character's ASCII code a few times. Obviously there's something wrong with my for-loop but I've been trying to figure it out and I really can't find it.

static String zin(String zin) {
  int length = zin.length();
  char letter = zin.charAt(0);
  int ascii = (int) letter;
    for (int i = 0; i < zin.length(); i++ ) {
    System.out.println((int) ascii);
    }
  return zin;
}
4

2 に答える 2

5

その理由は、再割り当てしないためですascii。これを試して:

static String zin(String zin) {
  int i = 0;
  int length = zin.length();

  for ( i = 0; i < zin.length(); i++ ) {
    int ascii = (int)zin.charAt(i);
    System.out.println(ascii);
  }

  return zin;
}
于 2014-09-11T15:52:35.313 に答える
0

コードの問題は、for ループがありますが、その for ループを使用して文字列を反復処理していないことです。その文字列の最初の文字のみを取得します。その使用の代わりに

    static String zin(String zin) {
        for (int i = 0; i < zin.length(); i++) {
            System.out.println((int) zin.charAt(i));
        }
        return zin;
    }
于 2014-09-11T15:54:02.983 に答える