将一串数字转换为数组
我在创建将数字字符串转换为数组的程序时遇到问题。
我知道这里有一个类似的问题,但我所要做的只是一组数字,例如 [10 15 16 0 57 438 57 18]
这是我到目前为止所拥有的:
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)
什么是我做错了吗?我想避免使用逗号来分隔元素。谁能解释为什么抛出异常以及如何修复它?我想了解比什么都重要。
i'm having problems creating a program that converts a string of numbers into an array.
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]);
}
}
}
this code throws throws an exception:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将字符串拆分一次并将数组存储在某处。
在这里,您将迭代到字符串中的字符数,而不是空格分隔的数字数。
更改为:
在线查看其工作情况:ideone
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.
Change to:
See it working online: ideone
正在发生的事情是这样的:
另外,您应该只执行一次 number.split(" ") 操作,然后像这样访问它:
所以基本上您的 for 确实是这样的:
然后numbers.split(" ") 返回只有 5 个元素,因为总共有 5 个数字,所以当你请求位置 6 时,会抛出异常,因为数组的大小只有 5。
Here is what is happening:
Aditionally you should just do this operation numbers.split(" ") once, and then just access it like this:
So basically your for is really something like this:
and then numbers.split(" ") returns only 5 elements, since there is a total of 5 numbers, so when you ask for position 6, the exception is thrown as the array is only of size 5.
我创建这个课程供我个人使用,但我认为它可以帮助您解决问题。
它可以这样使用:
I created this class for my own personal use but i think it can help you with your problem.
It can be used like this: