如何在正确的位置停止一个while循环?

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

How to stop a while loop in correct place?

问题

我需要帮助,因为我无法在正确的位置停止while循环。

在这个示例中,我想删除最后一个字符,只要字符串 "seq" 与列表中的某个数字(867)相同,然后停止。

更高级的做法是,在找到字符串后,将它们添加到新的ArrayList中,然后尝试查找其余的字符串(75)。如果找到,也要输入到新的数组中。

所有更好的解决方案都非常受欢迎。谢谢!

ArrayList列表可以包含数百个元素,但只有4个,列表中的一些元素可以重复多次。目前对我来说,只需在列表中找到第一个即可。如果找到,则将86775拆分为867:75。从字符串seq中删除867并添加到新的ArrayList中。最后,我们必须找到75 - 如果不存在,则拆分为7:5,并尝试查找7和5。在我的列表中,单个数字总是存在的,所以不会出现异常问题。

如果您想始终使用split方法,我需要尽可能找到更高的数字,然后如果找不到,则拆分并删除最后一个,但我需要每个数字。

正在检查的字符串可以有20个或更多字符。这是可能的最简单的示例。

我一直在寻找解决这个问题的许多方法,但我不确定这是否是最佳方法。

英文:

I need help because I can't stop the while loop in the correct place.
On this example, I want to remove the last char as long as the String "seq" will be the same as some number on the list (867), then stop.

More advanced is, after finding the String, to add them to new ArrayList, then try to find the rest of String (75). If found, also input to new Array.

All better solutions are very welcome. Thanks!

The ArrayList list can contain hundreds of elements, there are 4 only, some elements in the list can repeat more than one time. Find first on the list is fine for me at this moment. If found, split 86775 to 867:75. Remove 867 from String seq and add to new ArrayList. Finally, we have to find 75 - if it doesn't exist, split to 7:5, and try to find 7 and 5. On my list, single numbers always exist so no problem with exceptions.

If you want to use split method always I need to find the higher number as possible, then if not found split and removing last one but I need every digit.

The String being examined can have 20 chars or more. This is the simplest example possible.

I was looking for many methods to solve this problem and I am not sure this is best.

public class Main {
    public static void main(String[] args) {

        List<String> list = new ArrayList<String>();
        list.add("567");
        list.add("867");
        list.add("86");
        list.add("75");
        System.out.println(list);
        String seq = "86775";
        System.out.println(seq + ": found ?: " + getPatternFound(String.valueOf(list), seq) + " times");
        int nbChar = 0;
        do {
            getRemoveLastChar(seq, 1);
            if (getPatternFound(String.valueOf(list), seq) == 0) ;
            getRemoveLastChar(seq, 2);
            nbChar++;
            System.out.println(getRemoveLastChar(seq, nbChar));

        }
        while (nbChar < seq.length());

    }

    private static String getRemoveLastChar(String str, int nbChar) {
        return str.substring(0, str.length() - nbChar);
    }

    private static int getPatternFound(String longString, String pat) {
        Pattern pattern = Pattern.compile(pat);
        Matcher matcher = pattern.matcher(longString);
        int count = 0;
        while (matcher.find())
            count++;
        return count;
    }
}
[567, 867, 86, 30]
867755: found ?: 0 times
86775
8677
867 <- stop here
86
8

答案1

得分: 0

回答主要问题:完成后如何退出?

当然,你可以在循环中使用 breakcontinue 关键字来实现。我认为更加优雅的方式是在单独的方法中使用 return。如果以后需要进行更改,这会使代码更容易理解。

这是一个实现,展示了你所述的行为:

import java.util.ArrayList;

public class Test {
	public static void main(String[] args) {

		ArrayList<String> list = new ArrayList<String>();
		list.add("567");
		list.add("867");
		list.add("86");
		list.add("75");
		System.out.println("List = " + list);
		String seq = "86775";

		String result = search(list, seq);

	}

	/**
	 * 
	 * @param list
	 * @param seq
	 * @return null means no match;
	 */
	private static String search(ArrayList<String> list, String seq) {
		while (seq.length() > 0) {
			System.out.println("analyzing seq: " + seq);

			boolean broken = false;
			for (String s : list) {
				if (seq.contentEquals(s)) { // if matched

					System.out.println("found match: " + s);
					// do your logic, for example
					seq = seq.replace(s, "");

					// quit the loop at right place
					return s;
				}
			}
			seq = seq.substring(0, seq.length() - 1);

		}
		return null;
	}

}

生成输出:

List = [567, 867, 86, 75]
analyzing seq: 86775
analyzing seq: 8677
analyzing seq: 867
found match: 867

阅读你想要用它做什么时,String API 提供了 String.contains(String infix) 结合 String.replace(String old, String new)。这些方法应该比手动在循环中处理更好地解决你的实际问题。

英文:

To answer the main question: how do you quit when done?

Of course you can do it in-loop with the break or continue keywords.
What I deem more elegant is the use of return in a separate method.
It makes the code easier to understand if later you have changes.

Here is an implementation that shows the behaviour as you stated:

import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
list.add(&quot;567&quot;);
list.add(&quot;867&quot;);
list.add(&quot;86&quot;);
list.add(&quot;75&quot;);
System.out.println(&quot;List = &quot; + list);
String seq = &quot;86775&quot;;
String result = search(list, seq);
}
/**
* 
* @param list
* @param seq
* @return null means no match;
*/
private static String search(ArrayList&lt;String&gt; list, String seq) {
while (seq.length() &gt; 0) {
System.out.println(&quot;analyzing seq: &quot; + seq);
boolean broken = false;
for (String s : list) {
if (seq.contentEquals(s)) { // if matched
System.out.println(&quot;found match: &quot; + s);
// do your logic, for example
seq = seq.replace(s, &quot;&quot;);
// quit the loop at right place
return s;
}
}
seq = seq.substring(0, seq.length() - 1);
}
return null;
}
}

generates output:

List = [567, 867, 86, 75]
analyzing seq: 86775
analyzing seq: 8677
analyzing seq: 867
found match: 867

When reading what you want to do with it: the String API offers String.contains(String infix) in combination with String.replace(String old, String new) . These should solve your real problem much better than doing everything manually in loops.

huangapple
  • 本文由 发表于 2020年8月4日 01:32:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63234284.html
匿名

发表评论

匿名网友

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

确定