合并整数字符串

huangapple go评论83阅读模式
英文:

Merge strings of ints

问题

这是您提供的代码部分的翻译:

public static List<String> unifyNumbers(List<String> data) {
    List<String> temp = new ArrayList<String>();

    for (int i = 0; i < data.size(); i++) {
        String num = "";
        try {
            num += Integer.parseInt(data.get(i));
            for (int i2 = i; i < data.size(); i++) {
                try {

                    num += Integer.parseInt(data.get(i2));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    i = i2 - 1;
                    temp.add(num);
                    num = "";

                }

            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            temp.add(data.get(i));

        }
    }
    return temp;
}

请注意,代码中的变量名和注释均保持原样,未做翻译。

英文:

I am stuck ... can anyone tell me how can i do this:

Here is the required input and output:

input: [4, 2, +, 8, +, 2, 5, multiply sign, 2]

output: [42,+,8,+,25,multiply sign,2]

This was my last try and it output nothing :

public static List&lt;String&gt; unifyNumbers(List&lt;String&gt; data) {
		List&lt;String&gt; temp = new ArrayList&lt;String&gt;();
		
		for (int i = 0; i &lt; data.size(); i++) {
			String num = &quot;&quot;;
			try {
				num += Integer.parseInt(data.get(i));
				for (int i2 = i; i &lt; data.size(); i++) {
					try {
					
						num += Integer.parseInt(data.get(i2));
					} catch (NumberFormatException e) {
						e.printStackTrace();
						i = i2 - 1;
						temp.add(num);
						num = &quot;&quot;;

					}

				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				temp.add(data.get(i));

			}
		}
		return temp;
	}

答案1

得分: 1

import java.util.*;
import java.lang.*;
import java.io.*;

class Sample
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List<String> sampleData = new ArrayList<String>();
        sampleData.add("1");
        sampleData.add("2");
        sampleData.add("*");
        sampleData.add("8");
        sampleData.add("+");
        sampleData.add("2");
        sampleData.add("5");
        List<String> resultList = unifyNumbers(sampleData);
        System.out.println(resultList);
    }

    public static List<String> unifyNumbers(List<String> data) {
        String concatedNum = "";
        List<String> resultList = new ArrayList<String>();
        for(String arrVal: data) {
            if(isInteger(arrVal)) {
                concatedNum += arrVal;
            } else {
                resultList.add(concatedNum);
                resultList.add(arrVal);
                concatedNum = "";
            }
        }
        if(!concatedNum.isEmpty()) {
            resultList.add(concatedNum);
        }
        return resultList;
    }

    public static boolean isInteger( String input ) {
        try {
            Integer.parseInt( input );
            return true;
        }
        catch( Exception e ) {
            return false;
        }
    }
}
英文:
import java.util.*;
import java.lang.*;
import java.io.*;
class Sample
{
public static void main (String[] args) throws java.lang.Exception
{
List&lt;String&gt; sampleData = new ArrayList&lt;String&gt;();
sampleData.add(&quot;1&quot;);
sampleData.add(&quot;2&quot;);
sampleData.add(&quot;*&quot;);
sampleData.add(&quot;8&quot;);
sampleData.add(&quot;+&quot;);
sampleData.add(&quot;2&quot;);
sampleData.add(&quot;5&quot;);
List&lt;String&gt; resultList = unifyNumbers(sampleData);
System.out.println(resultList);
}
public static List&lt;String&gt; unifyNumbers(List&lt;String&gt; data) {
String concatedNum = &quot;&quot;;
List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
for(String arrVal: data) {
if(isInteger(arrVal)) {
concatedNum += arrVal;
} else {
resultList.add(concatedNum);
resultList.add(arrVal);
concatedNum = &quot;&quot;;
}
}
if(!concatedNum.isEmpty()) {
resultList.add(concatedNum);
}
return resultList;
}
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
}

答案2

得分: 1

i2变量不迭代,这就是为什么你没有得到任何输出。那个循环其实也是不必要的。将测试字符串是否为数字的部分放在自己的函数中会简化一些事情。

这是一个修订过的解决方案,以及一个可以测试的链接。
http://tpcg.io/l2xbRASM

public static Boolean isNumeric(String value) {
    try {
        Integer.parseInt(value);
        return true;
    } catch(NumberFormatException e) {
        return false;
    }
}

public static List<String> unifyNumbers(List<String> data) {
    List<String> temp = new ArrayList<String>();
    String num = "";

    for (int i = 0; i < data.size(); i++) {
        if(HelloWorld.isNumeric(data.get(i))) {
            num += Integer.parseInt(data.get(i));
        } else {
            temp.add(num);
            temp.add(data.get(i));
            num = "";
        }
    }
    if(num != "")
        temp.add(num);
    return temp;
}

我希望这能为其他人提供的答案增添一些内容。

英文:

The i2 variable doesn't iterate, which is why you are not getting any output. That loop isn't necessary anyway. Putting the test to see if a string is a number in its own function simplifies things a little.

Here is a revised solution, and a link to a place you can test it.
http://tpcg.io/l2xbRASM

public static Boolean isNumeric(String value) {
try {
Integer.parseInt(value);
return true;
} catch(NumberFormatException e) {
return false;
}
}
public static List&lt;String&gt; unifyNumbers(List&lt;String&gt; data) {
List&lt;String&gt; temp = new ArrayList&lt;String&gt;();
String num = &quot;&quot;;
for (int i = 0; i &lt; data.size(); i++) {
// HelloWorld is the name of the class I am testing this in.
if(HelloWorld.isNumeric(data.get(i))) {
num += Integer.parseInt(data.get(i));    
} else {
temp.add(num);
// this line adds the arithmetic operator to the resulting output
temp.add(data.get(i)); 
num = &quot;&quot;;
}
}
// add number that remains to the array
if(num != &quot;&quot;) 
temp.add(num);
return temp;
}

I hope this adds to the answers other people have given.

答案3

得分: 0

看起来Gowtham Nagarajan已经给了你一个更好的解决方法。我建议你使用他代码的修改版本,其中不使用try/catch块来检查你的字符串是否为整数(参见此问题讨论为什么你当前的方法并不是很好的做法)。

我仍然会展示给你我所做的更改,只是为了帮助你理解你的第一个方法出了什么问题,以及如何修复类似的问题。

我修改了你的代码,使其按照你的意愿工作。我用来查找问题的所有检查打印都还在里面,以便让你知道如何在执行过程中找出问题。这些检查可以更容易地跟踪程序的“流程”,并找出出了什么问题。你可以拿一张纸,写下程序的每一步,这些检查会显示出一切是否按照你的意愿工作,或者是否存在不必要的行为。

public static List<String> unifyNumbers(List<String> data) {
    List<String> temp = new ArrayList<String>();

    for (int i = 0; i < data.size(); i++) {
        String num = "";
        try {

            num = "" + Integer.parseInt(data.get(i));
            System.out.println("Check 1");

            for (int i2 = i + 1; i2 < data.size(); i2++) {

                try {

                    num += Integer.parseInt(data.get(i2));
                    System.out.println("Check 2");

                } catch (NumberFormatException e) {

                    System.out.println("Error inside loop");

                    e.printStackTrace();
                    i = i2 - 1;
                    System.out.println("To add:" + num);
                    temp.add(num);
                    num = "";
                    break;

                }

            }

        } catch (NumberFormatException e) {

            System.out.println("Error outside loop");

            e.printStackTrace();
            temp.add(data.get(i));

        }

        if (!num.equals("")) {
            System.out.println(num);
            temp.add(num);
        }
    }
    return temp;
}

在使用打印语句时,我发现你的原始代码从未离开第一个内循环。最后的System.out.println(num);语句打印出类似44444444的内容。诸如此类的提示可以帮助你使代码正常工作。

通过这种方式可以找出许多小错误,这样做相对容易。我建议你下次尝试这样做。祝你好运!

英文:

It seems like Gowtham Nagarajan already gave you a better way to do it. I'd advise you to use a modified version of his code, one that checks whether your String is an Integer without a try/catch block (see this question for a discussion on why your current approach isn't really good practice).

I'll still show you what I did, just to help you understand what went wrong with your first approch and how to fix something like that.

I changed your code to make it work like you want it to. All my check prints that I used to find problems are still in there, to give you an idea how to find problems in the execution. Checks like these make it easier to follow the "flow" of your program and to find out what went wrong. You can take a piece of paper and write down every step your program goes through, the checks will show you if everything works like you want it to or if there's unwanted behavior.

 public static List&lt;String&gt; unifyNumbers(List&lt;String&gt; data) {
List&lt;String&gt; temp = new ArrayList&lt;String&gt;();
for (int i = 0; i &lt; data.size(); i++) {
String num = &quot;&quot;;
try {
num = &quot;&quot; + Integer.parseInt(data.get(i));
System.out.println(&quot;Check 1&quot;);
for (int i2 = i + 1; i2 &lt; data.size(); i2++) {
try {
num += Integer.parseInt(data.get(i2));
System.out.println(&quot;Check 2&quot;);
} catch (NumberFormatException e) {
System.out.println(&quot;Error inside loop&quot;);
e.printStackTrace();
i = i2 - 1;
System.out.println(&quot;To add:&quot; + num);
temp.add(num);
num = &quot;&quot;;
break;
}
}
} catch (NumberFormatException e) {
System.out.println(&quot;Error outside loop&quot;);
e.printStackTrace();
temp.add(data.get(i));
}
if (!num.equals(&quot;&quot;)) {
System.out.println(num);
temp.add(num);
}
}
return temp;
}

When using the print statements, I found out that your original code never left the first inside loop. The print statement at the end System.out.println(num); printed something like 44444444. Hints like this one can help you make the code work.

There were a lot of small mistakes that were reasonably easy to find this way. I suggest you try that next time. Good Luck!

huangapple
  • 本文由 发表于 2020年10月18日 20:13:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64413153.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定