将一串数字转换为数组 [英] Convert a string of numbers into an array

查看:93
本文介绍了将一串数字转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建将一串数字转换为数组的程序时遇到问题。

i'm having problems creating a program that converts a string of numbers into an array.

我知道这里有类似的问题,但我必须处理的是一组数字,例如[10 15 16 0 57 438 57 18]

i know there is a similar question on here, but all i have to work with is a set of numbers such as [10 15 16 0 57 438 57 18]

到目前为止我所拥有的:

heres what i have so far:

import java.util.Scanner;
public class Histogram {

   public static void main(String[] args) {
     Scanner keyboard = new Scanner(System.in);
     String numbers;


     numbers = keyboard.next();
     System.out.println(numbers);

     int [] n1 = new int [numbers.length()];



     for(int n = 0; n < numbers.length(); n++) {
        n1[n] = Integer.parseInt(numbers.split(" ")[n]);
     }


}
}

此代码抛出抛出异常:

10 15 20 25 30
10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Histogram.main(Histogram.java:18)

我做错了什么?我想避免使用逗号分隔元素。任何人都可以解释为什么抛出异常以及如何解决它?我想了解更多。

what am i doing wrong? i want to avoid using commas to separate the elements. can anyone explain why the exception is being thrown and how to fix it? i want to understand more than anything.

推荐答案

您应该将字符串拆分一次并将数组存储在某处。

You should split the string once and store the array somewhere.

在这里,您将迭代到字符串中的字符的数量,而不是以空格分隔的数字的数量。

Here you are iterating up to the number of characters in the string, not the number of space-separated numbers.

int [] n1 = new int [numbers.length()];
for(int n = 0; n < numbers.length(); n++) {
   n1[n] = Integer.parseInt(numbers.split(" ")[n]);
}

更改为:

String[] parts = numbers.split(" ");
int[] n1 = new int[parts.length];
for(int n = 0; n < parts.length; n++) {
   n1[n] = Integer.parseInt(parts[n]);
}

看到它在线工作: ideone

这篇关于将一串数字转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆