简体   繁体   English

是否可以将String转换为int数组?

[英]Is String to int Array conversion possible?

I've written that piece of code in which I scanned an integer suppose 121 and for dividing it into 3 part I make it a String and tried to convert it again by splitting.But I am not getting the way? 我已经编写了一段代码,其中我扫描了一个整数假设121,并将其分为3部分,我将其设置为String并尝试通过split再次将其转换。但是我不明白吗? Is there any simple way to make it so? 有没有简单的方法可以做到这一点?

  public static void main(String []args){
      Scanner scan = new Scanner(System.in);
      int n = scan.nextInt() ;
      int sum = 0;
      for(int i = 1 ; i<=n; i++){
         String s = Integer.toString(i);

          int[] c = Integer.parseInt(s.split("")); //Here's the problem
          int sm = 0 ;
          for(int x :c){
              sm +=x ;
          }
          System.out.print(sm+" ");
       }
   }

input = 12 输入= 12

expected output: 1 2 3 4 5 6 7 8 9 1 2 3 预期输出:1 2 3 4 5 6 7 8 9 1 2 3

output : Main.java:14: error: incompatible types: String[] cannot be converted to String int[] c = Integer.parseInt(s.split("")); 输出:Main.java:14:错误:不兼容的类型:String []无法转换为String int [] c = Integer.parseInt(s.split(“”));

Your expected output would not even seem to need any integer to string conversion: 您的预期输出似乎甚至不需要任何整数到字符串的转换:

int n = scan.nextInt();
for (int i=0; i < n; i++) {
    if (i > 0) System.out.print(" ");
    System.out.print(1 + i % 9);
}

For an input of n = 12 , this prints: 对于n = 12的输入,将输出:

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

You can't pass the whole array to parseInt() . 您不能将整个数组传递给parseInt() You need to parse each element individually: 您需要分别解析每个元素:

int[] c = Arrays.stream(s.split(""))
        .mapToInt(Integer::parseInt)
        .toArray();

Or the old-fashioned way: 还是老式的方式:

String[] chars = s.split("");
int[] c = new int[chars.length];
for (int i = 0; i < c.length; i++) {
    c[i] = Integer.parseInt(chars[i]);
}

You could map each character from the String[] (from the split ) to an int , and then convert that to an int[] . 可以String[]每个字符(从split )映射到int ,然后将其转换为int[] Like, 喜欢,

int[] c = Arrays.stream(s.split("")).mapToInt(Integer::parseInt).toArray();

with no other changes, that produces (as requested) 没有其他更改,就会产生(按要求)

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

With input of "12". 输入“ 12”。

You can also do it like this using an IntStream. 您也可以使用IntStream这样操作。


    int n = 12;
    int[] values = IntStream.range(0, n).map(i -> i % 9 + 1).toArray();
    System.out.println(Arrays.toString(values));

Produces 产生

[1 2 3 4 5 6 7 8 9 1 2 3] [1 2 3 4 5 6 7 8 9 1 2 3]

for n = 12 对于n = 12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM