这段代码有问题(抱歉,我不能具体)

时间:2013-11-17 02:15:09

标签: java arrays loops char

尝试编写一个程序,该程序将char数组(ch)的值分配为65到90.然后我会尝试打印它:

    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z

我试图用两个循环来做这件事,有很多麻烦。这就是我到目前为止所做的:

    import java.util.*;
    public class Lab10a {
        public static void main(String[] args) {
            char ch[] =new char[26];
            for (int x = 0; x < ch.length; x++){
                ch[x] = (char)(x + 65);
                for(int i = 0, i < ch.length; i++)[


                }
            }
     //It doesn't need to be converted to a string here, this is just a method i tried.
                System.out.println(Arrays.toString(ch) + ", ");
        }
    }

这是我目前的打印输出:

    [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z], 

很抱歉我的编码很不清楚,真的不太确定如何解决这个问题。建议?

5 个答案:

答案 0 :(得分:0)

这样做

        for (int x = 0; x < ch.length; x++){
            ch[x] = (char)(x + 65);                
        }

        for(int i = 0, i < ch.length; i++){
             if((ch.length-1)==i){
                  System.out.print(ch[i]);
             }else{
                  System.out.print(ch[i] + ", ");
             } 
        }

答案 1 :(得分:0)

String out = "";
for (int i = 0; i < ch.length; i++)
     out += ", " + ch[i];
System.out.println(out.subString(2));

答案 2 :(得分:0)

你可以试试这个

public static void main(String[] args) {
  char ch[] =new char[26];
  for (int x = 0; x < ch.length; x++){
      ch[x] = (char)(x + 'A');
  }
  // System.out.println(Arrays.toString(ch));
  boolean first = true;
  for (char c : ch) {
    if (! first) {
      System.out.print(", ");
    }
    System.out.print(c);
    first = false;
  }
  System.out.println();
  System.out.flush();
}

答案 3 :(得分:0)

经过测试并正常工作

import java.util.*;
public class Lab10a {
   public static void main(String[] args) {
      char ch[] =new char[26];
      for (int x = 0; x < ch.length; x++){
          ch[x] = (char)(x + 65);
      }

      // for every char in the char array (except the last one), 
      // print it with a comma 
      for (int i = 0; i < ch.length - 1; i++) 
          System.out.print(ch[i] + ", ");

      System.out.print(ch[ch.length - 1]); // print the last one without a comma
   }
}

答案 4 :(得分:0)

你可以做,你做了什么,但也使用str = str.replace()。

例如:

String str = Arrays.toString(ch);
str = str.replace(",", "");
str = str.replace("[", "");
str = str.replace("]", "");

然后只需打印字符串。

尚未对此进行测试,但应该可行。