Java 如何从字符数组打印字符和整数

Java 如何从字符数组打印字符和整数,java,Java,我的字符串数组为char[]onlyar={'A'、'B'、'C'、'D'、'1'、'2'、'3'、'4'}; 我该怎么做 A,1 B,2 C,3 D,4 使用语法[字母][数字]你真的应该首先自己做一些研究,如果有,拿出证据。然而,这里有一个解决方案 int halfLength = onlyArr.length / 2 + (onlyArr.length % 2); for(int i = 0; i < halfLength; i++){ System.out.printf(

我的字符串数组为char[]onlyar={'A'、'B'、'C'、'D'、'1'、'2'、'3'、'4'}; 我该怎么做

A,1
B,2
C,3
D,4

使用语法[字母][数字]

你真的应该首先自己做一些研究,如果有,拿出证据。然而,这里有一个解决方案

int halfLength = onlyArr.length / 2 + (onlyArr.length % 2);
for(int i = 0; i < halfLength; i++){
    System.out.printf("%c,%d%n", onlyArr[i], (int)(onlyArr[i + halfLength] - 48));
}
打印整数时,必须从字符中减去ascii值“0”48,然后将结果转换为整数


半长的分配可能会得到优化,但此代码将执行您希望它执行的操作。

您可以在onlyArr中同时从左侧和右侧开始,并相应地打印:

char[] onlyArr={'A','B','C','D','1','2','3','4'};

int n=onlyArr.length;
int i=0,j=(n)/2;

while(i<n/2)
{
    System.out.println(onlyArr[i]+""+onlyArr[j]);
    i++;j++;

}
假设定义为char[]数组={'A','B','C','D','1','2','3','4'};,我知道你们想把这些元素联系起来,以你们的例子来说,我会这样做

// Arrays are fixed-length and here we also know the sequence
// Individual judgment is anyway required to establish the right pattern

for (int i = 0; i< array.length/2; i++)
    System.out.println(array[i]+","+array[i+4]);

如果要写入数组的值,语法如下:

String[] myString = {1, 2, 3}
System.out.println(myString[0]); 
// OUTPUT-> 1. Be careful. Position 0 it is the first in all arrays
System.out.println(myString[1]); // OUTPUT -> 2
// .....
要打印所有值,应使用foreach循环:

Foreach使用数组是一种简短的形式,因为您避免创建计数器。与此相同:

for(count = 0; count < onlyArr.length; count++){
    System.out.println(onlyArr[count]);
}
如果你想写:1,A.2,B.3,C。。。您可以使用普通for循环:

for(count = 0; count < onlyArr.length; count++){
    System.out.println(v + ", " + onlyArr[count]);
}

你没有一个字符串数组,但是一个字符数组只是为了清楚起见,但是,你还必须保存数字?Appologize…更正..谢谢:它不是一个字符串数组检查第一个代码段的语义和语法。这甚至不是有效的Java。回答得好。就像我想的。。。
for(count = 0; count < onlyArr.length; count++){
    System.out.println(v + ", " + onlyArr[count]);
}