猿问

使用 if 和 else 语句之外的字符串来设置字符串值

关于我遇到的问题,我只是有一个足够简单的问题。我试图设置一个字符串值,"0"如果一个 webelement 不存在,否则字符串是 webelement 值(使用getText)。但是,我似乎无法在if 和 else语句之外使用这些值。我该怎么做呢?


这是我的代码


String players_in_game = null;


public void join_game_user_increases_register() throws Exception {


    WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);

    wait.until(ExpectedConditions.visibilityOf(countdownLabel));


    if (!num_of_players_in_game.isDisplayed()) {

        String players_in_game = "0";

    } else {

        String players_in_game = num_of_players_in_game.getText();

    }


    System.out.println(players_in_game);

    int first_num = Integer.parseInt(players_in_game);


慕的地6264312
浏览 161回答 3
3回答

开心每一天1111

使用下面的代码:WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);wait.until(ExpectedConditions.visibilityOf(countdownLabel));String players_in_game = "0";if(num_of_players_in_game.isDisplayed()){&nbsp; &nbsp;players_in_game = num_of_players_in_game.getText();&nbsp; &nbsp;}System.out.println(players_in_game);int first_num = Integer.parseInt(players_in_game);或者:String players_in_game = num_of_players_in_game.isDisplayed() ? num_of_players_in_game.getText() : "0";或者:List<WebElements> num_of_players_in_game = driver.findElements(By....);String players_in_game = num_of_players_in_game.size()==0 ? "0": num_of_players_in_game.get(0).getText();

梦里花落0921

你可以试试这个:String players_in_game = null;public void join_game_user_increases_register() throws Exception {WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);wait.until(ExpectedConditions.visibilityOf(countdownLabel));try {&nbsp; &nbsp; if (num_of_players_in_game.isDisplayed()) {&nbsp; &nbsp; &nbsp; &nbsp; String players_in_game = num_of_players_in_game.getText();&nbsp; &nbsp; }} catch (Exception e) {&nbsp; &nbsp; String players_in_game = "0";}System.out.println(players_in_game);int first_num = Integer.parseInt(players_in_game);

万千封印

由于您已经在代码的第一行中将该变量声明为类成员,因此String只需删除即可不将该名称重新声明为局部变量,而是使用该字段:if(!num_of_players_in_game.isDisplayed()){&nbsp; &nbsp; players_in_game = "0";} else {&nbsp; &nbsp; players_in_game = num_of_players_in_game.getText();}
随时随地看视频慕课网APP

相关分类

Java
我要回答