使用Split将所有新元素添加到ArrayList并使用混合输入。

时间:2013-10-19 22:01:05

标签: java arraylist split java.util.scanner

我正在使用split来分割字符串输入。前3个工作正常,因为它们是字符串,但最后一个输入是双。任何想法我应该如何使这个工作,所以字符串拆分然后可以将结果[4]传递给ArrayList中的double?

Scanner catin = new Scanner(System.in);
System.out.print("Enter the Name, Breed, Color, and Weight of the Cat: ");
String test = catin.nextLine();
String[] result = test.split(","); 
Cat c4 = new Cat(result[1], result[2], result[3], result[4]);

2 个答案:

答案 0 :(得分:2)

不太确定你想要什么,但我认为你是在Double.parseDouble(result[4])之后:

Cat cat = new Cat(result[1], result[2], result[3], Double.parseDouble(result[4]));

再次注意索引。索引应为0 --> 3,因为数组是基于零的索引。

答案 1 :(得分:1)

你的索引错了。应该是:

Cat c4 = new Cat(result[1], result[2], result[3], Double.parseDouble(result[4]));

数组是零索引的,并解析您的weight String