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

这是我想要实现的目标。


输入:


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但也得到了与上面相同的输出。如何纠正这个?


倚天杖
浏览 205回答 3
3回答

料青山看我应如是

您可以使用Arrays.asList和streamAPI去解决。limit在你的情况下,我曾经将记录数限制为 5。如果您的病情发生变化,您可以使用filter并将您的病情放在那里。下面是一个关于如何完成的小代码片段public static void main(String[] args) {&nbsp; &nbsp; String[] s = "1 2 3 -4 -5 -6 -7 -8 -9".split(" ");&nbsp; &nbsp; Arrays.asList(s).stream().limit(5).forEach(System.out::print); // filter&nbsp; &nbsp;// or use below to get the first five element list&nbsp; &nbsp;Arrays.asList(s).stream().limit(5).collect(Collectors.toList());}

一只斗牛犬

您可以尝试字符串操作。@Testpublic void stringManipulationForArray() {&nbsp; &nbsp; int[] intArray = {1,2,3,4,5,6,7,8};&nbsp; &nbsp; final String arrayAsStr = Arrays.toString(intArray);&nbsp; &nbsp; System.out.println(arrayAsStr );&nbsp; &nbsp; final String numbersWithCommas = arrayAsStr .substring(1, s.length() - 1);&nbsp; &nbsp; System.out.println(numbersWithCommas);&nbsp; &nbsp; final String numbersWithoutCommas = numbersWithCommas.replace(",", "");&nbsp; &nbsp; System.out.println(numbersWithoutCommas);}

守候你守候我

尝试Arrays.toString(s)代替s.toString().更正后的代码如下所示:String[] s = sc.nextLine().split(" ");for(int i=0;i<n;i++){&nbsp; &nbsp; ...}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();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java