[英]How to create an array of integers in char type?
I am trying to create an array of integers in char type for a given dimension.我正在尝试为给定的维度创建一个 char 类型的整数数组。 For instance if the dimension is 5 the array should be {'1', '2', '3', '4', '5'}, however I am not getting any output.例如,如果维度是 5,则数组应该是 {'1', '2', '3', '4', '5'},但是我没有得到任何输出。
public static void main(String[] args) {
int dim = Integer.parseInt(args[0]);
char [] num = new char[dim];
for(int i = 49; i < dim; i++){
for(int j = 0; j < dim; j++){
num[j] = (char) i ;
}
System.out.println(num);
}
}
Here I changed the code, I added an initial value ascii = 49: But still I am not getting the desired output :(在这里我更改了代码,我添加了一个初始值 ascii = 49:但是我仍然没有得到所需的输出 :(
public static void main(String[] args) {
int dim = Integer.parseInt(args[0]);
char [] num = new char[dim];
int ascii = 49;
for(int i = 0; i < dim; i++){
for(int j = 0; j < dim; j++){
num[j] = (char) (ascii + i) ;
}
System.out.println(num);
}
}
int dim = Integer.parseInt(args[0]);
for(int i = 49; i < dim; i++){
dim
will need to be over 49 for the body of this loop to execute, and indeed there is output when you do so. dim
需要超过 49 才能执行此循环的主体,并且当您这样做时确实会有输出。
Edit: With the new code, the inner loop writes the same value over the entire array.编辑:使用新代码,内部循环在整个数组上写入相同的值。 The outer for loop does this for incrementing values, printing the array out each time.外部 for 循环这样做是为了增加值,每次打印出数组。
Are you trying to do你想做什么
num[j] = (char) (ascii + j);
but perhaps without the outer for loop.但也许没有外部 for 循环。
Your issue might be here in the first for loop:您的问题可能出现在第一个 for 循环中:
for(int i = 49; i < dim; i++){
The for loop will never be entered unless dim is greater than 49 (since you've specified i as 49 with the condition that dim must be greater than i [or i must be less than dim] for the loop to be executed.除非 dim 大于 49,否则永远不会进入 for 循环(因为您已将 i 指定为 49,条件是 dim 必须大于 i [或 i 必须小于 dim] 才能执行循环。
If the first for loop is never entered, the print statement is never reached.如果从未进入第一个 for 循环,则永远不会到达打印语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.