3 回答
TA贡献1943条经验 获得超7个赞
你需要这样的东西:
public static void main(String[] args) {
int val;
int evcounter = 0;
int odcounter = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter total no of elements ");
val = sc.nextInt();
System.out.println("Enter values ");
String[] n = new String[val];
String[] eve = new String[(int) Math.ceil(val/2D)];
String[] odd = new String[val/2];
for (int i = 0; i < n.length; i++) {
n[i] = sc.next();
if (i % 2 == 0) {
eve[evcounter] = n[i];
evcounter++;
} else {
odd[odcounter] = n[i];
odcounter++;
}
}
System.out.println("Even array: " + Arrays.toString(eve));
System.out.println("Odd array: " + Arrays.toString(odd));
}
TA贡献1921条经验 获得超9个赞
如果您使用的是 1.8+,那么最好使用易于理解且优雅的函数式风格。
import java.util.Arrays;
import java.util.function.IntPredicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class MyTestCase {
@Test
public void evenOddStringArrayPrinting() {
String[] src = new String[] {"HI", "Hello", "Bye"};
final String[] evenArray = getArrayFrom(src, i -> i % 2 == 0);
final String[] oddArray = getArrayFrom(src, i -> i % 2 == 1);
System.out.println(Arrays.toString(evenArray));
System.out.println(Arrays.toString(oddArray));
Assert.assertEquals(2, evenArray.length);
Assert.assertEquals(1, oddArray.length);
}
private String[] getSome(final String[] src, final IntPredicate predicate) {
return IntStream.range(0, src.length)
.filter(predicate)
.mapToObj(i -> src[i])
.collect(Collectors.toList())
.toArray(new String[] {});
}
}
TA贡献1790条经验 获得超9个赞
public static void main(String[] args) {
int evenCounter = 0;
int oddCounter = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter total no of elements ");
int num = reader.nextInt();
String[] n = new String[num];
System.out.println("Enter values:");
for (int i=0;i<n.length;i++)
{
n[i]=reader.next();
if (i % 2 == 0) {
evenCounter++;
}
else
{
oddCounter++;
}
}
String[] even = new String[evenCounter];
String[] odd = new String[oddCounter];
for (int z=0;z<n.length;z++)
{
if (z%2==0)
{
for (int j=0;j<even.length;j++)
{
if (even[j]==null)
{
even[j]=n[z];
break;
}
}
}
else if (z%2==1)
{
for (int j=0;j<odd.length;j++)
{
if (odd[j]==null)
{
odd[j]=n[z];
break;
}
}
}
}
这个想法是遍历原始 String 数组并检查它的索引是否为偶数/奇数(就像您在代码中所做的那样检查有多少赔率/偶数)。如果索引是偶数,则遍历 evens 数组并检查数组的第一个空单元格(在 java 中,当您生成字符串数组时,您会得到一个充满空值的数组,因此您搜索第一个空值并将其替换为值来自原始数组)。赔率也一样。
添加回答
举报