每行打印10个字符

时间:2015-03-28 02:51:59

标签: java methods

你好我在这个问题上编码时遇到了一些麻烦;

编写一个使用以下标题打印字符的方法: public static void printChars(char ch1,char ch2,int numberPerLine) 此方法使用每行指定的数字打印ch1和ch2之间的字符。编写测试程序,从'l'和'Z'每行打印10个字符。

有人能告诉我编码样本来解决我的问题吗?感谢

2 个答案:

答案 0 :(得分:0)

字符以ASCII编码。每个字符都有一个唯一的十进制数表示。我们可以通过数字来访问这些字符,而不是实际字符。

例如,字符'A'的ASCII码为65.虽然我们并不需要知道整数代码来使用它们各自的字符表示。我们可以将整数强制转换为char s。

我们也可以在简单算术中使用字符。由于'A'具有ASCII码65,因此65 + 1 = 66表示字符'B'是有意义的。确实如此。

public static void printChars(char ch1, char ch2, int numberPerLine) {
   if(ch1 <= 'Z' && ch2 >= 'a')
      return;

   int count = 0; //count number of characters on a line.
   char nextChar = ch1; //initialize our next character

   while(nextChar <= ch2) { //test case
      System.out.print(nextChar);
      count++; //once we print a character, increment our count

      if(count == numberPerLine) { //check if we reach our desired amount of characters
         System.out.println();
         count = 0; //once we print a new line, restart the count
      }

      nextChar = (char) (nextChar + 1); //get next character
   }
}

答案 1 :(得分:0)

以下是一些似乎适用于我的代码。

public static String alphabet = "abcdefghijklmnopqrstuvwxyz";

public static void printChars(char ch1, char ch2, int numberPerLine){
    int currentNumber = numberPerLine;

    int beginningIndex = alphabet.indexOf((ch1 + "").toLowerCase()) + 1;
    int endingIndex = alphabet.indexOf((ch2 + "").toLowerCase());

    for(int i = beginningIndex; i < endingIndex; i++){
        System.out.print(alphabet.charAt(i));
        if(currentNumber > 1){
            currentNumber --;
        }else{
            System.out.println("");
            currentNumber = numberPerLine;
        }

    }
}

public static void main(String[] args) {
    printChars('c', 'z', 2);
}
相关问题