简体   繁体   English

Java:将字符串解析为int并计算总和

[英]Java: parse string to int and compute the sum

First off I want to start by saying I'm not just looking for someone to give me the answer to this problem, I am a beginner programmer and am just trying to learn as much as possible. 首先,我首先要说的是,我不仅仅是在寻找某人来给我解决这个问题的方法,我还是一名初学者,并且正尝试着学习尽可能多的东西。 A critique of my code and a friendly nudge in the right direction would be most appreciated! 最好是对我的代码进行批评并朝着正确的方向友好地推动! What is really confusing me is my stringParser method. 真正令我困惑的是我的stringParser方法。 I use this method to loop through the string, picking out the numbers and storing them in a new string to be parsed. 我使用这种方法来遍历字符串,挑选出数字并将它们存储在要解析的新字符串中。 What confuses me is how I would be able to add these numbers together? 让我困惑的是如何将这些数字加在一起? Here is the code: 这是代码:

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;
}

As per my guess, you want to parse something like this `12 + 34 = '. 据我的猜测,您想解析类似“ 12 + 34 =”的内容。

If I'm right, then your for loop is completely wrong. 如果我是对的,那么您的for循环是完全错误的。 It will return only 34 as integer value. 它将仅返回34作为整数值。 You can debug your code for that. 您可以为此调试代码。

I suggest you something like this : 我建议你这样:

int index = 0;
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);
    }           
    newArray[index++] = parsed; //make sure you initialize newArray.
}      
return newArray;

Try, 尝试,

String parsee = "12+13 = 34+45 = 45+-45";
int value = 0;
String parsed = "";
for(String exp : parsee.split("=")){            
    for(String val : exp.trim().split("\\+")){
        value+=Integer.parseInt(val);
    }
    parsed+=" SUM = "+value;
    value = 0;
}
System.out.println(parsed);

Output 产量

 SUM = 25 SUM = 79 SUM = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM