How to get rid of certain parts of a string input? - java

I just started my first programming class and I am trying to write a program that uses JOption dialogue boxes and can't seem to figure out how to create the right output. I am trying to have the user enter a URL into the dialogue input box, and have an output dialogue box display just the website name without the www. or the .com portion. Thanks in advance!
public static void main(String[] args)
{
String input= JOptionPane.showInputDialog(null,
"Please enter website URL");
String.output=JOptionPane.showMessageDialog(null,
)

There is a method in java called replace() that would be perfect for this scenario.
For learning knowledge, the method looks like this(it is built in) :
public String replace(char oldChar, char newChar)
But in order to call it, you can put in your string . replace of course with the parameters.
input.replace("www" , "") //Makes the www blank
I recommend putting these into switch/if statements.
if (input.contains ("www") {
input.replace("www" , "") //Makes the www blank
}
Now, if you also want to get rid of .com if it exists, then:
if(input.contains(".com"){
input.replace(".com", "")
}
Thats it. First, check if the user entered the stuff you don't want using .contains, and if they did remove it using .replace.
~{Rich}

Related

How to pass conditional varible in using Selenium Java?

private static final String Accept = "Accept & continue";
public void acceptWorkspaceCreation() {
//Wait for Set up a Work Profile Screen for Android 9 Pixel
waitUtilByText(180, Accept);
assertTrue("Couldn't click on Accept & continue.",
findElementByIdAndClick("com.android.managedprovisioning", "next_button"));
}
public boolean waitUtilByText(int seconds, String text){
String textStr = "//*[#text='" + text + "//*[#id='";
return !new WebDriverWait(this.driver, seconds).until(ExpectedConditions.presenceOfAllElementsLocatedBy(By
.xpath(textStr))).isEmpty();
}
For some cases Accept value comes in caps 'ACCEPT & CONTINUE', How to validate both the strings in selenium.
The condition you are waiting for only checks for one thing:
ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(textStr))
So, presumably (as I am not familiar with Selenium), you can use the ExpectedConditions.or method to check a number of conditions, and wait for just one to be true:
ExpectedConditions.or(
ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(textStr)),
ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(textStr2)))
where textStr2 is the alternative text you are looking for.
I'd suggest using native Android UiSelector's textMatches method where You'd write matcher for both upper and lower case texts. If you want to stick to the Xpath anyways - it also has a text matcher. But first of all, investigate why the text changes - that's not a good practice.

If Statement Providing Wrong Output

I coded a banking program. I'm at the point where the user must enter their pin, and it must be compared to their pin which is taken from a text file. The problem is, I have an if statement, and the condition is met, but it keeps giving me an the statement as if it was not met.
I've tried switch statements and even using a boolean value, but it does not work
public String getPin(){
return pin;
}
String pin2 = lbl_Pin.getText();
System.out.println(pin2);
System.out.println(getPin());
// Allows the user to select what they want to do after they enter the
// correct pin
if (pin2.equals(String.valueOf(getPin()))) {
btn_SelectLoan.setEnabled(true);
btn_SelectWithdraw.setEnabled(true);
btn_SelectDeposit.setEnabled(true);
btn_Balance.setEnabled(true);
lbl_Loan.setVisible(true);
lbl_Withdraw.setVisible(true);
lbl_Deposit.setVisible(true);
lbl_Balance.setVisible(true);
}
// Displays invalid if the pin is not correct
else {
lbl_Pin.setText("Invalid");
}
I enter the correct pin, I am sure of this as I displayed the correct pin as well as the entered pin, and they are the same, but an invalid answer is provided
It might be an encoding issue. When you are reading the pin from the text file, please make sure that the encoding of the text matches with that of lblP=_Pin.
When you are reading the text file, you can mention the desired encoding while opening the file.
I found the issue. When getting the Pin from the text file, '/r' was added on as part of the value. So I just made a substring with the actual value of the pin.

Selenium made a sendKeys for two fields instead of one for some reason

I made a pretty simple selenium test, where I want to open web page, clear field value, start entering text for this field, select first value from the hint drop down.
Web site is aviasales.com (I just found some site with a lot of controls, this is not an advertisement)
I did
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).clear();
and it was working perfectly, I also checked via console that this is the only one object on a page like:
document.getElementById('flights-origin-prepop-whitelabel_en')
So, in next line I'm sending value:
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).sendKeys("LAX");
but it send LAX value for both "flights-origin-prepop-whitelabel_en" and "flights-destination-prepop-whitelabel_en" for some reason, then i tried
DriverFactory.getDriver().findElement(By.id("//input[#id='flights-destination-prepop-whitelabel_en'][#placeholder='Destination']")).sendKeys(destinationAirport);
but I got the same result:
What could be a reason and how to fix this?
Thank you!
Yep... there's some weird behavior going on there. The site is copying whatever is entered into the first field into the second for reason I don't understand. I gave up trying to understand it and found a way around it.
Whenever I write code that I know I'm going to reuse, I put them into functions. Here's the script code
driver.navigate().to(url);
setOrigin("LAX");
setDestination("DFW");
...and since you are likely to use these repeatedly, the support functions.
public static void setOrigin(String origin)
{
WebElement e = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(origin);
e.sendKeys(Keys.TAB);
}
public static void setDestination(String dest)
{
WebElement e = driver.findElement(By.id("flights-destination-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(dest);
e.sendKeys(Keys.TAB);
}
You can see the functions but basically I click in the field, clear the text (because usually there's something already in there), send the text, and then press to move out of the field and choose the default (first choice).
The reason of your issue is the ORIGIN and DESTINATION inputbox binded keyboard event which used to supply an autocomplete list according to your typed characters.
The binded keyborad event breaks the normal sendKeys() functionality. I met similar case in my projects and questions on StackOverFlow.
I tried input 'GSO' into DESTINATION by sendKeys('GSO'), but I get 'GGSSOO' on page after the sendKeys() complete.
To resolve your problem, we can't use sendKeys(), we have to use executeScript() to set the value by javascript in backgroud. But executeScript() won't fire keyborad event so you won't get the autocomplete list. So we need find out a way to fire keyborady event after set value by javascript.
Below code snippet worked on chrome when i tested on aviasales.com:
private void inputAirport(WebElement targetEle, String city) {
String script = "arguments[0].value = arguments[1]";
// set value by javascript in background
((JavascriptExecutor) driver).executeScript(script, targetEle, city + "6");
// wait 1s
Thread.sleep(1000);
// press backspace key to delete the last character to fire keyborad event
targetEle.sendKeys(Keys.BACK_SPACE);
// wait 2s to wait autocomplete list pop-up
Thread.sleep(2000);
// choose the first item of autocomplete list
driver.findElement(By.cssSelector("ul.mewtwo-autocomplete-list > li:nth-child(1)")).click();
}
public void inputOrigin(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
return inputAirport(target, city);
}
public void inputDestination(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepopflights-destination-prepop-whitelabel_en"));
return inputAirport(target, city);
}

Hide/Show Password in a JTextFIeld (Java Swing)

So I've been working on a Password Strength Checker and the way it works is that the user enters some random text into a textfield and then instantaneous visual feedback (breakdown of points) is displayed. I've also added a checkbox, which on being selected, should hide the password i.e. replace all the chars with asterisks, while preserving the actual text input by the user. A document listener is being used to keep track of changes inside the textfield. (each char on entry gets analyzed and then scored)
So, my question is, how exactly do I mask the user input with asterisks preserving its original value?
Here's what the GUI looks like:
http://speedcap.net/sharing/screen.php?id=files/51/2f/512f9abb3f92a25add7c593e9d80e9e4.png
How exactly do I mask the user input with asterisks preserving its original value?
Use the JPasswordField which has nice function jPasswordField.getPassword(); to get the password as char[] to work with.
Use jPasswordField1.setEchoChar('*') to mask the password characters with *.
If you wish to see the value you are inserting use jPasswordField1.setEchoChar((char)0); Setting a value of 0 indicates that you wish to see the text as it is typed, similar to the behavior of a standard JTextField.
Tutorial and Reference:
How to use Password Fields
setEchoChar(char)
Use Password Field Instead of using textfield
ok thanks for tutorialnya,
and ex,
action chechbox / double click
private void lihatActionPerformed(java.awt.event.ActionEvent evt) {
if (lihat.isSelected()) {
password.setEchoChar((char)0); //password = JPasswordField
} else {
password.setEchoChar('*');
}
}
I solved it as follows:
if ( jPasswordField.getEchoChar() != '\u0000' ) {
jPasswordField.setEchoChar('\u0000');
} else {
jPasswordField.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
}

sendKeys.RETURN not working in FirefoxDriver

if I execute the following code in FireFoxDriver:
WebElement element = driver.findElements(By.id("some_id")); // element being a textbox
element.sendKeys("apple");
element.sendKeys(Keys.RETURN);
The sendKeys(Keys.RETURN) is not performing its desired function.
Actually what I am trying to do is Input a text in a dynamic text search box (like one in facebook search) and press enter. The input is working fine but not the enter key.
sendKeys("apple") works, even sendKeys(Keys.BACK_SPACE) works, but not Keys.RETURN.
Does anyone have ideas? Thanks guys!
Not exactly sure why this happens, but there are a couple alternate ways of doing this that may help:
If elements are in a form, and there is no javascript that runs on submit or something you can use .submit() on any form input element, such as inputs and textareas:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple");
element.submit()
You can send the newline character with your input:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple\n");
Provide send_keys a list:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple", Keys.ENTER);
Got the solution to the above problem. U just need to add, a delay.
This happens because the Java Class runs too fast, so if u have sent a call, and pressed enter/ tab, before the element arrives, the enter is pressed, that is why this doesn't work. Just add Thread.delay(1000); before your Keys.RETURN command. That will do.
Worked for me.
I tried sending \n and fiddled with various commands until I found someone explaining that "keyPress (target) 13" will send the return key.
So first I use type to enter the string I want ...
*
*<tr>
<td>type</td>
<td>id=status</td>
<td>This is my test string</td>
</tr>*
*
... and then send the Enter key to the same text input box
*
*<tr>
<td>keyPress</td>
<td>id=status</td>
<td>13</td>
</tr>*
*

Categories