I'm a beginner and can't work out why this loop won't break.
I need to delete some users and for each user i'm prompted if i'm sure i want to delete the user.
so i made the following loop:
while (!alert && delete_button_is_present)
{
clickDeleteBtn;
if(alert)
{
driver.switchTo().alert().accept();
}
else if(delete_button_is_not_present)
{
break;
}
}
Problem is after all users are deleted and delete button is not present anymore the test is still looking for the button.
Make sure delete_button_is_present is or at least can be modified in either clickDeleteButton or driver.switchTo().alert().accept(), or that condition can never be met.
Some questions I have about your code though, which might help if they get cleaned up: you have delete_button_is_present and delete_button_is_not_present. You can get rid of not_present and just use !delete_button_is_present. Why do you have an else if which isn't paired with an if inside if(alert)? If you mean for this to be if(alert), then if(!delete_button_present) then you just need an if statement. Otherwise you want that else if outside the if(alert).
Lets walk through your code
while (!alert && delete_button_is_present)
{
clickDeleteBtn;
if(alert)
{
driver.switchTo().alert().accept();
else if(delete_button_is_not_present)
{
break;
}
}
You're saying that you want to continue this loop as long as there is no alert, and there is a delete button present on the screen. First, you click the delete button. Without any information about what this button does, I'll assume it is not relevant to the loop. You say if(alert), but if there was an alert you wouldn't be in the loop in the first place...So the loop repeats
Related
I have an API that on each call return me a random document from MongoDB collection.
This is code:
AtomicInteger countSummerCamps = new AtomicInteger();
#GetMapping("/getRandomSummerCamps")
public String getRandomSummerCamps(Model model) {
countSummerCamps.incrementAndGet();
if (getCountSummerCamps() <= adventureHolidaysService.countAdventureHolidays("summerCamps")) {
model.addAttribute("randomSummerCamps", adventureHolidaysService.findRandomAdventureHolidays("summerCamps"));
return "randomSummerCamps";
} else {
return "noMoreDoc";
}
}
What is my problem and how I tried.
So in this situation the program will return me four elements in HTML. And after that the program will show me a noMoreDoc page. That works fine. But the problem is when I refresh the page. It’s still page noMoreDoc even if I go on the home page and hit the API again. It’s still the noMoreDoc page. I want to avoid that and after the user refreshes the page and get back on /getRandomSummerCamps show the user random documents again on every call.
I tried to set counterSummerCamps.set(0) inside }else{, but I got "Unreachable statement".
Is there a way to fix this, so after the user got the noMoreDoc page and after the user get back on, to /getRandomSummerCamps show the user random documents again on each call?
If you call counterSummerCamps.set(0) after the return statement of else, you will get unreachable code. Try to set it before the return statement.
I'm writing a Java Game similar to Tetris for a school project. In the game I have a checkbox to turn music on/off.
My problem is that the checkbox, even though I set it to be checked, is NOT checked when I click it (don't understand me wrong, not AFTER, but before/at the same moment when I clicked it).
Okay so, in my code where I first initialize the checkbox I set it to be checked based on a variable provided in another class.
I tried debugging everything that is going on with the checkbox but I didn't get anything I didn't already knew.
Here's the code where I initialize the box:
music_cbox = TexturesHandler.getCheckboxTemplate();
music_cbox.setName("Music");
music_cbox.addMouseListener(Retris.getButtonHandler());
music_cbox.setLocation(Retris.WIDTH / 2 - 25, 250);
// Setting it to checked based on the variable
if(!Retris.getAudioHandler().canPlay()) {
music_cbox.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
music_cbox.setSelected(false);
System.out.println("box not selected");
} else {
music_cbox.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
music_cbox.setSelected(true);
System.out.println("box selected");
}
The canPlay variable only gets changed when you CLICK the box:
if(box.isSelected()) {
Retris.getAudioHandler().canPlay(false);
Retris.getAudioHandler().stopMusic();
System.out.println("Music disabled");
box.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
break;
// (in a switch statement)
} else {
Retris.getAudioHandler().canPlay(true);
Retris.getAudioHandler().startMusic("Main_Menu.wav", "Main Menu", 0.1F);
System.out.println("Music enabled");
box.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
break;
}
I also tried box.setSelected() after setting the new icon and all, but somehow when i first click the box, it does the else part instead of the if part.
Not sure if this helps but I noted that in the initialization you call music_cbox.setSelected() but then in your if statement you call box.isSelected()
Are these the same box? Could explain why you set the variable but then check another one.
On my page, I have alerts that display sometimes. (these are actually notifications in Salesforce) These alerts break my scripts since my scripts can't find the elements behind the alerts. I'd like to check for the alerts and if they exist, dismiss them. If they don't exist, then move on to the next step.
Secondary problem is that there may be more than one of these alerts. So it may have dismiss anywhere from 1 to 6 or more alerts.
I've added this code to my test script and it works if there is ONE alert. Obviously my script fails if there is more than one alert or if there are zero alerts.
driver.findElement(By.xpath("//button[contains(#title,'Dismiss notification')]")).click();
I'm still learning java, so please be gentle. ;) But I'd love to put this into a method so it can look for those buttons, click if they exist, keep looking for more until it finds none, then move on. I just have no idea how to do it.
I'm using TestNG too, I know that makes a difference in what's allowable and what's not.
Thank you!
You can use wait with try/catch to get all buttons and click on each if exist.
1.If alerts all appear at once use code below:
try{
new WebDriverWait(driver, 5)
.ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.cssSelector("button[title*='Dismiss notification']"))))
.forEach(WebElement::click);
} catch (Exception ignored){ }
2.If alerts appear singly use code below:
try{
while(true) {
new WebDriverWait(driver, 5)
.ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("button[title*='Dismiss notification']"))))
.click();
}
} catch (Exception ignored){ }
Use findElements which will return a list of 0 if the element does not exist.
E.G:
List<WebElement> x = driver.findElements(By.xpath("//button[contains(#title,'Dismiss notification')]"));
if (x.size() > 0)
{
x.get(0).click();
}
// else element is not found.
findElements will return the list no need of creating one again. Also x.size() won't work because list object has no attribute size so we have to check the length. No need of using x.get(0).click();.
driver.click(By.xpath("//button[contains(#title,'Dismiss notification')]")) should work.
x = driver.findElements(By.xpath("//button[contains(#title,'Dismiss notification')]"));
if (len(x) > 0) {
x.click();
}
I am trying to create a GUI for my program. This particular GUI uses a JOptionsPane with a showOptionDialog. I have added a panel to that OptionsPane that has some action listeners as well as two lists and some other things, that really doesn't matter for this question though.
Quite simply I want my showOptionDialog to perform some action when the user clicks the "cancel" button. (It will basically end the program but it must be done in a certain way). Right now when the user clicks "cancel" the program continues as if the user just ended that dialog but no action is taken. I am trying to change a variable if they click cancel which will prevent the rest of the program from running. I tested with a System.out.println to see if my value was really being changed and I found that the step wasn't occurring at all. So I would like to know based upon this code what I am doing wrong. What do I need to do to make the code run correctly when the user clicks cancel?
I do not have more code to show as my program is very large and it is impossible for me to isolate this situation.
Thanks in advance for the help!
public static void displayGUI(){
int result = JOptionPane.showOptionDialog(null, getPanel(),"JOptionPane Example : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Confirm","Create Return"}, "default");
if(result == JOptionPane.CANCEL_OPTION){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
}
*This part of the code isn't being executed, even if the user selects cancel:
if(result == JOptionPane.CANCEL_OPTION){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
From your Question:
*This part of the code isn't being executed, even if the user selects cancel:
Try The integer value that is returned from the JOptionPane.showOptionDialog(). 0 Is returned if OK is selected and 1 is returned if Cancel is selected.
Modify your code as follows:
if(result == 1){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
Let me Know, If this doesn't Helps you!!!
You are telling JOptionPane to create two buttons ("Confirm" and "Create Return"), and then telling it the default button is "default" but you don't have a button with text "default". You also don't have a Cancel". The return value will be 0 if the uses picks "Confirm", or 1 if the user picks "Create Return", or CLOSED_OPTION if the user just closes the dialog.
If you take a look at the JavaDocs for JOptionPane.showOptionDialog, it tells you
Returns: an integer indicating the option chosen by the user, or
CLOSED_OPTION if the user closed the dialog
This is the index of the options array you passed to the method. In this case new String[]{"Confirm","Create Return"}
So a return value of 0 will mean Confirm was selected and 1 will mean Create Return was selected (or JOptionPane.CLOSE_OPTION if the user closed the window)
When assigning result a value you are using JOptionPane.OK_CANCEL_OPTION but in the if condition you are checking for JOptionPane.CANCEL_OPTION
I'd like to check for an existing file using a while loop. Now the problem is, that if use something like this:
while (file.exists()) {
text.setText("Some text appears");
text.setTextColor(Color.RED);
}
my program always seem to not to respond at all. Is it because my loop is somehow an infinite loop? Or why is is not working correctly.
Right now, i am using a simple if statement but i don't like it that way, because it is not updated right away when the file exists.
EDIT:
What i want is:
I offer a file to download. In my app, there is a text which says "Not Available yet". I want to change the text right after the file exists to something like "File is Available".
If you want to check periodically if a file exists, you have to do this with an asynchronous task or a timer.
TTimerTask task = new TimerTask() {
#Override
public void run() {
// Here you do whatever you want
}
};
Timer timer = new Timer();
timer.schedule(task, 0,30000);
This will check the file every thirty seconds.
You can find more info on http://www.mkyong.com/java/jdk-timer-scheduler-example/
Your program goes in an infinite loop as the condition inside while loop will always be true if the file is present..
You need to check like this:
File file = new File(subDir.getPath() + "somefile.txt");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
}
else
{
//Update here
}
And if you want to check it inside the loop then try like this:
while (true)
{
File file = new File(subDir.getPath() + "somefile.txt");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
return;
}
else
{
//Update here
}
}
If the file exists, then it'll pop into the while loop and will keep on looping because the file exists, you'll have to make the file non-existable within the while loop...
Best thing for you to do, is get your program working without the while loop... as you mentioned with an IF function, then slowly over time implement (Test) a new function (while loop) into the equation.
What you need to fix in the while loop is... What happens to the file when it enters the loop and how does it get out of the loop. Current standing is, it doesn't as the file still exists.
Ok so whenever the other person is checking for the file does the program exit if the file doesn't exist? I mean you can't just have it checking for the file forever. I suppose you could put it in a Thread and run it with a slight wait inside the while loop but the overhead... sheesh!
Is this a specific screen inside your program? Is the person suppose to be able to exit this "file found/not found" page? I could probably write a snippet but I need more info. :)