有没有办法在java中切断String Array(不使用循环)并直接转换为整数?

问题描述 投票:0回答:3

这就是我想要实现的目标。

输入:

5
1 2 3 -4 -5 -6 -7 -8 -9

预期产出:

The list is 1 2 3 -4 -5.
There are 3 positive numbers and 2 negative numbers.

示例代码:

String[] s = sc.nextLine().split(" ");
for(int i=0;i<n;i++)
{
    ...
}
System.out.printf("The list is %s.\nThere are %d positive numbers and %d negative numbers",(s.toString().substring(0,n)),pos,neg);
sc.close();

现在输出:

The list is [Ljav.
There are 3 positive numbers and 2 negative numbers.

尝试用Integer.parseint(s.toString().substring(0,n))应用%d但是也获得了与上面相同的输出。怎么纠正这个?

java arrays string
3个回答
2
投票

您可以使用Arrays.asListstream API来获得解决方案。我已经使用limit将记录数量限制为5,就像你的情况一样。如果您的情况发生变化,您可以使用filter并将您的病情放在那里。下面是一个如何完成它的小代码片段

public static void main(String[] args) {
    String[] s = "1 2 3 -4 -5 -6 -7 -8 -9".split(" ");
    Arrays.asList(s).stream().limit(5).forEach(System.out::print); // filter
   // or use below to get the first five element list
   Arrays.asList(s).stream().limit(5).collect(Collectors.toList());
}

1
投票

你可以尝试字符串操作。

@Test
public void stringManipulationForArray() {

    int[] intArray = {1,2,3,4,5,6,7,8};
    final String arrayAsStr = Arrays.toString(intArray);
    System.out.println(arrayAsStr );
    final String numbersWithCommas = arrayAsStr .substring(1, s.length() - 1);
    System.out.println(numbersWithCommas);
    final String numbersWithoutCommas = numbersWithCommas.replace(",", "");
    System.out.println(numbersWithoutCommas);
}

0
投票

试试Arrays.toString(s)而不是s.toString()

更正后的代码如下所示:

String[] s = sc.nextLine().split(" ");
for(int i=0;i<n;i++)
{
    ...
}
System.out.printf("The list is %s.\nThere are %d positive numbers and %d negative numbers",(Arrays.toString(s).substring(0,n)),pos,neg);
sc.close();
© www.soinside.com 2019 - 2024. All rights reserved.