如何将这些打印的字母存储到数组中? [英] How do I store these printed letters into an array?

查看:79
本文介绍了如何将这些打印的字母存储到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在这个程序打印出字母表(az)但是我想把这些字母存储起来并将每个字母存储在名为leta的数组中,我该怎么做?

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 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;i<=lettter;i++ ) {  
            System.out.print((char)i);
        }
    }
}


推荐答案

这几乎是一个语法类型的问题,但它也很棘手,指出它的工作原理有一些价值。

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. 单引号中的字符与 char 类型的整数相同。您可以分配它们并对它们进行数学运算。我认为这使得初始分配 char letterA ='a'; 比使用数字65更清楚。

  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.

如前所述,您也可以使用字符类型进行数学运算。请注意,计算aray索引 [i-'a'] ,以便第一个字符从65中减去65,以便'a'存储在索引0中,并且从那里开始。这有点棘手,但从长远来看,我认为更简单,也比在你面前用ASCII表编程更容易。

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.

这篇关于如何将这些打印的字母存储到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆