Eclipse不打印空字符

时间:2017-01-23 22:57:32

标签: java eclipse

我在Eclipse中编写了一个java程序。让我们说我声明一个数组:

char[] array = new char[5];

然后我只初始化了几个元素。当我尝试打印整个数组时,Eclipse会在到达未初始化元素时停止,并且什么都不做。另一方面,当我使用javac命令在终端中编译它时,它工作正常,并为未初始化的元素打印空格(或者我应该说空字符)。为什么会这样?

编辑:这是完整的代码(程序发现子数组只接受原始字母的字母)

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input=new Scanner(System.in);

    int n=4;
    char[] array=new char[n];
    System.out.println("Input array elements: ");
    for(int i=0; i<n; i++){
        array[i]=input.next().charAt(0);
    }
    char[] A=new char[n];
    int j=0;
    for(int i=0; i<array.length; i++){
        if ((array[i]>=65 && array[i]<=90)||(array[i]>=97 && array[i]<=122)){
            A[j]=array[i];
            j++;
        }

    }

    System.out.printf("subarray is A=[ ");
    for(int i=0; i<n; i++){
            System.out.printf(A[i]+" ");
    }
    System.out.printf("].");
}

例如,如果输入是st1p,则输出[stp并停在那里。不执行最后一次打印。

1 个答案:

答案 0 :(得分:2)

那是因为char属性的默认值是'\ u0000'(空字符),如Java语言规范中所述,§4.12.5 Initial Values of Variables .

我修改并创建了一个小项目,将单词转换为字符串并完全打印出来。它也打印数字。我希望这可以帮助你找到你想要的东西。 当然,您可以创建其他char数组并填充每个第二个字母,第三个等等,并获得每个单词的每个子字符串的第n个总的char数组。就像你一样。

 public class stringToArray {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter string: ");
        String word = input.next();

        int index = word.length(); // get index of word to create array of exact length
        char[] chars = new char[index]; // create the array of exact length

        System.out.print("The char array from the String is: ");
        for (int i = 0; i < chars.length; i++) {
            chars[i] = word.charAt(i); // populate the char array with the word, by breaking the word in chars 

            System.out.print(chars[i] + " "); // print it to check that it is working
        }

    }
}