关于我遇到的问题,我只是有一个简单的问题。如果没有Webelement,我尝试将字符串值设置为id = 1
,否则该字符串就是Webelement值(使用 id desc mfr group
0 0 This is text ABC 0
1 1 John Doe ABC DEF 0
2 2 John Doe DEF 0
3 3 Something JKL GHI 1
4 4 Something more JKL 1
)。但是,我似乎无法在 if and else 语句中使用这些值。我该怎么做呢?
这是我的代码
"0"
答案 0 :(得分:5)
使用以下代码:
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();
答案 1 :(得分:1)
由于您已经在代码的第一行中将该变量声明为类成员,因此只需删除String
即可不将其重新声明为局部变量,而应使用字段:
if(!num_of_players_in_game.isDisplayed()){
players_in_game = "0";
} else {
players_in_game = num_of_players_in_game.getText();
}
答案 2 :(得分:1)
Java允许在类级别进行可变阴影。因此,实际上您可以在任何方法中声明一个与类变量同名的变量。在您的情况下,变量名称为players_in_game
。
您可以在方法中再次定义该变量,但是该新变量的范围将有所不同。因此,如果要在方法中设置该类级别的String,请不要定义新变量并使用该类级别的变量。
因此只需使用以下代码:
if (!num_of_players_in_game.isDisplayed()) {
players_in_game = "0";
} else {
players_in_game = num_of_players_in_game.getText();
}
已经有人用代码回答了。我只想解释原因。
答案 3 :(得分:1)
您可以尝试以下方法:
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);