为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地6264312 2021-09-12 20:22:07
关于我遇到的问题,我只是有一个足够简单的问题。我试图设置一个字符串值,"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);
查看完整描述

3 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

使用下面的代码:


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

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


String players_in_game = "0";

if(num_of_players_in_game.isDisplayed()){

   players_in_game = num_of_players_in_game.getText();   

}


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();



查看完整回答
反对 回复 2021-09-12
?
梦里花落0921

TA贡献1772条经验 获得超6个赞

你可以试试这个:


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 {

    if (num_of_players_in_game.isDisplayed()) {

        String players_in_game = num_of_players_in_game.getText();

    }

} catch (Exception e) {

    String players_in_game = "0";

}


System.out.println(players_in_game);

int first_num = Integer.parseInt(players_in_game);


查看完整回答
反对 回复 2021-09-12
?
万千封印

TA贡献1891条经验 获得超3个赞

由于您已经在代码的第一行中将该变量声明为类成员,因此String只需删除即可不将该名称重新声明为局部变量,而是使用该字段:


if(!num_of_players_in_game.isDisplayed()){

    players_in_game = "0";

} else {

    players_in_game = num_of_players_in_game.getText();

}


查看完整回答
反对 回复 2021-09-12
  • 3 回答
  • 0 关注
  • 160 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信