首先,我想先說我不只是在尋找某人給我這個問題的答案,我是一名初學者程序員,我只是想學習儘可能多。對我的代碼的批評以及對正確方向的友好推動將非常感謝!真正讓我困惑的是我的stringParser方法。我使用這種方法遍歷字符串,挑出數字並將它們存儲在一個新字符串中進行解析。令我困惑的是如何將這些數字加在一起?這裏是代碼:Java:將字符串解析爲int並計算總和
public static int stringParser(String parsee,int parsed)
{
int indexOfString = parsee.indexOf("="); //Searches for an = sign since there has to be one
String parsee2 = "";
int [] newArray;
String subStringParse = parsee.substring(0,indexOfString); //Substring made to divide string, this one is from 0 index to 1st occurence of =
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
} return parsed;
}
public static int sumInts(int a,int storedSums)
{
//a = new int[20];
for(int i=0;i<a;i++) //loops through parsed string from stringParser
{
storedSums += a; //creates a new value calculating sum
}
return storedSums;
}
你能提供一個例子輸入字符串? –
感謝您的迴應!用戶輸入字符串的示例如下所示:1 + 2 = 3 + 4 = 5 + -6 =。輸出將是:SUM = 3 SUM = 7 SUM = -1。目標是計算每個'='符號前的值的總和。 – user3251584