我在編寫一個程序,其中用戶輸入一系列數字作爲字符串,然後程序將字符串拆分爲不同的數字,按類型對它們進行分類,將它們一起列出按組,然後將它們加在一起。例如,用戶輸入1,5,3L,284L,4.3和2.34。然後程序將1和5一起列出,3和284一起列出,4.3和2.34列在一起。然後,程序顯示編號299.64。但是,我收到一個錯誤。我會發布我迄今爲止的內容。任何想法可能來自我的問題?謝謝。列出不同類型的數組值並添加它們
這是我的錯誤:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1, 2L, 3.3"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at change.NumberArray.Convert(NumberArray.java:21)
at change.TestNumberArray.main(TestNumberArray.java:9)
代碼:
package change;
import java.util.ArrayList;
import java.util.Scanner;
public class NumberArray {
static Scanner s = new Scanner(System.in);
public static void Convert(){
System.out.print("Enter numbers by: ");
String input = s.nextLine();
String[] inputString = input.trim().split(" , ");
int i = 0;
ArrayList<Long> listLong = new ArrayList<Long>();
ArrayList<Double> listDouble = new ArrayList<Double>();
ArrayList<Integer> listInt = new ArrayList<Integer>();
while (i < inputString.length){
if (inputString[i].contains("L")){
long temp = Long.parseLong(inputString[i]);
listLong.add(temp);
i++;
}
else if (inputString[i].contains(".")){
double temp = Double.parseDouble(inputString[i]);
listDouble.add(temp);
i++;
}
else{
int temp = Integer.parseInt(inputString[i]);
listInt.add(temp);
i++;
}
}
System.out.println("Here are the long numbers you entered:");
for (int q = 0; q < listLong.size(); q++)
{
System.out.println(listLong.get(q));
}
System.out.println("Here are the double numbers you entered:");
for (int q = 0; q < listDouble.size(); q++)
{
System.out.println(listDouble.get(q));
}
System.out.println("Here are the integer numbers you entered:");
for (int q = 0; q < listInt.size(); q++)
{
System.out.println(listInt.get(q));
}
System.out.println("Here is the sum of the numbers you entered: ");
double sum = 0;
for (int z = 0; z < inputString.length; z++)
{
sum = sum + Double.parseDouble(inputString[z]);
}
System.out.print(sum);
}
}
你得到什麼錯誤? –
將其添加到原始帖子。謝謝@JasonC – GoldenEarring