How do I store these printed letters into an array?

后端 未结 2 1012
名媛妹妹
名媛妹妹 2021-01-26 12:45

Right now this program prints out the alphabet (a-z) however I want to take those letters and store each one in the array called leta, how do i do that?

public c         


        
相关标签:
2条回答
  • 2021-01-26 13:05

    This is almost a "syntax" type question, but it's also tricky enough that there's some value to pointing out how it works.

    class Arrayofhope
    {
    
       public static void main( String[] args )
       {
          char[] leta = new char[ 26 ];
          char letterA = 'a';
          char letterZ = 'z';
          for( int i = letterA; i <= letterZ; i++ ) {
             System.out.print( (char) i );
             leta[i-'a'] = (char)i;
          }
       }
    }
    
    1. Characters in single quotes are the same as integers of type char. You can assign them and do math on them. I think this makes the initial assignment of char letterA = 'a'; more clear than using the number 65.

    2. And as mentioned you can do math with character types too. Note the aray index [i-'a'] is calculated so that 65 is subtracted from 65 for the first character, so that 'a' is stored in index 0, and proceeding up from there. This is kinda tricky but in the long run more clear, I think, and also easier than trying to program with an ASCII table in front of you.

    0 讨论(0)
  • 2021-01-26 13:08
     public class Arrayofhope {
     public static void main (String[]args) {
     char []leta = new char[26];
     char letter = (char)65;
     char lettter=(char)90;
     for (int i = letter,j=0;i<=lettter;i++,j++ ) {
    
    let[j] = (char)i;
    

    // If you don't want new variable you can do like below

    let[i-65] = (char) i;
    
    
    System.out.print((char)i);
    
    }
    }
    }
    
    0 讨论(0)
提交回复
热议问题