java - (Java) 如何让程序重试某些操作,直到获得特定值?

标签 java string treeview

我正在制作一个程序,可以根据分支的名称过滤TreeView中的信息(分支)。

我创建了一种从 TreeView 菜单中获取随机 branch 的方法,只要 branch 包含 String > "=s=". 方法如下:

public TreeItem<String> randomBranch(TreeItem<String> parent){
    Random rand = new Random();
    int listNum = parent.getChildren().size();

    int num = rand.nextInt(listNum) + 0;

    TreeItem<String> getIT = parent.getChildren().get(num);

    if(getIT.toString().contains("=s=")){
        return getIT
    }
    else{
    (Missing_code_here)
    }
}

我不知道要在else中放入什么。但我想要它,所以它会重新尝试,直到找到包含 "=s="branch 。 我该怎么做?

最佳答案

如果我正确理解了这个问题,那么您所需要的只是一个简单的循环。

public TreeItem<String> randomBranch(TreeItem<String> parent) {

    Random rand = new Random();
    int listNum = parent.getChildren().size();

    int num;
    TreeItem<String> getIT;

    do {
        num = rand.nextInt(listNum) + 0;
        getIT = parent.getChildren().get(num);
    } while (!getIT.toString().contains("=s="));

    return getIt;
}

当然,如果结构不包含带有字符串 "=s=" 的项目,您将陷入无限循环。

关于java - (Java) 如何让程序重试某些操作,直到获得特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131734/

相关文章:

c# - 为什么 Sun 不做 C# 到 Java 字节码编译器?

java - 将参数从 HTML 发送到 Java Applet

java - 尝试使用按钮作为导航菜单时未处理的异常类型

Java正则表达式替换文本中的字符串

perl - 如何在 Perl Tkx 中实现带滚动条的可调整大小的 TreeView 小部件?

javafx - 在CellFactory中有条件地提供不同的TreeCell

java - 将 jaxb xml 消息转换为 apache camel 中的基本类型(java)

结构打印垃圾中的字符数组

javascript - 在visjs中右键单击节点(上下文菜单)打开扩展弹出窗口(html列表)

c - C中字符串的奇怪排序