Passing returned variable to other method - java

I have problem, because I have method where I return a variable and I need to compare it, but I don't know how to get it...
My code:
public char setCurrency(String currencyToSet) {
WebElement currencyVal = driver.findElement(By.name(currencyToSet.toUpperCase()));
String currencyName = currencyVal.getText();
System.out.println("Currency Name:" + currencyName);
currencyVal.click();
char[] currencyNameArray = currencyName.toCharArray();
char newCurrencySymbol = currencyNameArray[0];
System.out.println(newCurrencySymbol);
return newCurrencySymbol;
}
public char[] getCurrentCurrencySymbol(){
return currentCurrencySymbol.getText().toCharArray();//string??
}
I want to read in other method newCurrencySymbol.
Updated:
#Test
public void changeCurrency() {
topNav.clickCurrencyDropDown();
char nowa = topNav.setCurrency("eur");
Assert.assertEquals(topNav.getCurrentCurrencySymbol(), nowa);
}
And I get an error:
java.lang.AssertionError: expected [€] but found [[C#74f6c5d8]
should be € but is C#74f6c5d8
But when I print this variable in 8th line, it trow €, but not passing it
I'm changing currency (left top) on enter link description here and want to compare

First of all, you're comparing between a char array (getCurrentCurrencySymbol()) and a char (nowa). Former is an object whereas latter is a primitive data type. When you try to compare the two, you will get some weird values such as C#74f6c5d8 like you see. That's the address of where the char array is actually being stored.
I would suggest that you change from char array to simply a char since they're supposed to be currency notations. This ways, the comparison between the two values will be simplified.

Related

How to add a char into an array using add?

I am trying to coding Java and adding a char to an array. My idea is compare two char, if they are different, I will add them to an array and here is my code.
ArrayList<String> different = new ArrayList<>();
if (character.charAt(i) == (character.charAt(i+1)))
{
}
else
{
different.add(character.charAt(i+1));
}
But when I run my code, they said to me that "no suitable method found for add (char)" at line 6, and I can not run the code. Could you please give me some ideas? Thank you very much for your help.
The problem is that you are adding char datatype to an arraylist which is of type String. You need to change the code to:
ArrayList<Character> different = new ArrayList<>();
if (character.charAt(i) != (character.charAt(i + 1))) {
different.add(character.charAt(i + 1));
}
String::charAt returns a char, not a String. So your char cannot be put into a list holding String objects. Square peg, round hole.
Also char is a legacy type, limited to a subset of less than half of the over 110,000 characters defined in Unicode, restricted to code points in the “basic plane”. You should learn to work with code points as numbers to be able to handle any Unicode characters.
When you declared List<String> or ArrayList<String>, it means the List should contain type String or literals(something between double quote "". FYI, this is called Generic Type.
Use String#valueOf(char c) to create new String from a char. Example:-
//returns a type char
char c = character.charAt(i+1);
//use String#valueOf(char c) to create new `String` from variable `c`
different.add(String.valueOf(c));
** Oracle has good tutorial on Generic Type, you could refer to it.
https://docs.oracle.com/javase/tutorial/java/generics/index.html
ArrayList<Character> different = new ArrayList<>();
if (character.charAt(i) == (character.charAt(i+1)))
{
}
else
{
different.add(character.charAt(i+1));
}
///////////////////
Just add Wrapper class Character instead of String.

Printing integer to textfield area

Im having a trouble in java. Im creating a HRRN scheduling. I want to print the integer that I input into a textfield area. Please help me to solve this problem. Thankyou!
private void AWTActionPerformed(java.awt.event.ActionEvent evt) {
int firstprocess=1;
if (bt1.getText().equals("")){
double tempbt1 = Double.parseDouble(bt1.getText());
awttotalprocess = (firstprocess + (tempbt1));
AWTCLICK = 0;
jtf_awt.setText(String.valueOf(awttotalprocess+"ms"));
}
I want to print the awttotalprocess into jtf_awt.
Bracketing issue:
jtf_awt.setText(String.valueOf(awttotalprocess)+"ms");
Many classes come with what's called a .toString() method that prints a pre-specified output when joined with a string. You can concatenate or join a string and a variable -in this case an integer- like this:
int i = 50;
String join() {
return "I'm a string, next is a number: " + 50;
}
Keep in mind that int and Integer are different in that the first is a primitive data type, and the second is the object. This isn't an issue for you in this code but in the future if you try to concatenate a string with an object it may end up printing out the memory address as written in the .toString() default method and would require you to #override the method to specify your own string output. The primitive data types are "easier" to combine and don't require such .toString() overriding or .valueOf() shenanigans.

how to pass a variable through sendKeys in selenium webdriver?

I want to pass the float variable 'f' through sendKeys in the below program.Can someone please let me know the same? As of now, it is throwing
"The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments ".
Code:
public static String isEditable(String s1) {
f=Float.parseFloat(s1);
System.out.println(f);
boolean bool=webDriver.findElement(By.xpath("expression")).isEnabled();
if(bool) {
if((f<0) || (f>6)) {
error="Value must be between 0.00% and 6.00%";
System.out.println(error);
} else {
webDriver.findElement(By.xpath(""expression")).sendKeys(f);
}
} else {
error="Please enter a valid Number";
}
return error;
}
Convert the float to a string:
webDriver.findElement(By.xpath("...")).sendKeys(Float.toString(f));
I know you already accepted an answer but I wanted to clean up your code a little and give you some feedback.
I changed the name of the function because a function named isEditable() should return a boolean indicating whether some field is editable. That's not what your function is doing so it should be given a more appropriate name. I made a guess at what the actual name should be... I could be way off but you should name it something more along the lines of what it's actually doing... putting text in a field.
I removed the isEnabled() check because that should be done in the function that sets the fund number. Each function should do one thing and only one thing. This function validates that the rate passed is in a valid range and then puts it in the field.
I removed the duplicate code that was scraping the INPUT twice. Just do it once, save it in a variable, and reuse that variable. In this case, there's no need to scrape it twice.
and as d0x said, you shouldn't convert the s1 string to a float and then back to string when you sendKeys() ... just send the s1 string. Translating it back doesn't help readability, it just means you wrote more code that someone after you will need to understand. Favor clean code... it's always more readable.
public static String enterRate(String s1)
{
f = Float.parseFloat(s1);
WebElement input = webDriver.findElement(By.xpath(".//*[#id='p_InvestmentSelection_4113']/div/div/div[5]/div/ul/li/div[3]/div[2]/label/div[1]/input"));
if ((f < 0) || (f > 6))
{
error = "Value must be between 0.00% and 6.00%";
}
else
{
input.sendKeys(s1);
}
return error;
}
Can you try passing s1 instead of f. Because the method takes a string, not a float.
Your method should look like this:
String selector = "expression";
webDriver.findElement(By.xpath(selector)).sendKeys(f);
And please use better variable names like userInput instead of s1 or userInputAsFloat instead of f or investmentInputVisible instead of bool etc.

If a char array is an Object in Java, why does printing it not display its hash code?

Printing a char array does not display a hash code:
class IntChararrayTest{
public static void main(String[] args){
int intArray[] = {0,1,2};
char charArray[] = {'a','b','c'};
System.out.println(intArray);
System.out.println(charArray);
}
}
output :
[I#19e0bfd
abc
Why is the integer array printed as a hashcode and not the char array?
First of all, a char array is an Object in Java just like any other type of array. It is just printed differently.
PrintStream (which is the type of the System.out instance) has a special version of println for character arrays - public void println(char x[]) - so it doesn't have to call toString for that array. It eventually calls public void write(char cbuf[], int off, int len), which writes the characters of the array to the output stream.
That's why calling println for a char[] behaves differently than calling it for other types of arrays. For other array types, the public void println(Object x) overload is chosen, which calls String.valueOf(x), which calls x.toString(), which returns something like [I#19e0bfd for int arrays.
The int array is an array of integers where as the char array of printable characters. The printwriter has the capability to print character arrays as this is how it prints string anyway. The printwriter will therefore print them like a string, without calling the toString() method to convert it to a string. Converting an int array to a string returns a hash code, explaining why you get that output.
Take this for example:
int[] ints = new int[] { 1, 2, 3 };
char[] chars = new char[] { '1', '2', '3' }
If you were to print both those sequences using the method you used, it would print the hash code of the int array followed by '123'.
System.out is PrintStream which has a special method for char[] arg
public void println(char x[]) {
synchronized (this) {
print(x);
newLine();
}
}
int[] is printed via this method
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
Ofcourse arrays are objects in Java. No matter what type of array it is. It is always an object in Java.
But as far as your question is concerned, there is a method, println(char[] array), in java.io.PrintStream class that prints out all characters from a char array. And that is the reason, when you pass a char[] as a parameter to println(), it doesn't call the toString() method of the java.util.Array class, but rather loops through the array and prints every character.
Citation:
http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(char[])
System.out actually gives you an Object of PrintStream. and its println(params) has some overloaded methods which are implemented differently for different type of params.
This params if being a char[] provides the output as char[] elements like System.out.println(charArray); outputs abc but not the hashcode as in the case of int[] like System.out.println(intArray); outputs [I#19e0bfd.
PS :- All the array are treated as Object in Java.
See the Official Doc
Moreover, for printing array, always use the Arrays utility class. Its method Arrays.toString() should be preferably used for printing array objects.
The other answers correctly explain your case of a separate call to PrintStream.println and the same is true for .print. However your title could cover other ways of printing. PrintWriter.println and .print AND .write do have char[] overloads for a simple call.
However, formatting does not have a special case:
System.out.format ("%s%n", charArray); // or printf
myPrintWriter.format ("%s%n", charArray); // or printf
each outputs [C#hash, similar to the handing of int and other type arrays.
Nor does concatenation, often used in printing:
System.out.println ("the value of charArray is " + charArray);
outputs the value of charArray is [C#hash.

"The left-hand side of an assignment must be a variable" problem with charAt

private String kNow(String state, String guess) {
for (int i = 0; i < word.length(); i++) {
if (guess.equals(word.charAt(i))) {
state.charAt(i) = word.charAt(i);
}
}
return state;
}
state.charAt(i) part points the problem in the title.
How can I solve the problem, if my approach is not completely wrong.
The reason this doesn't work is because charAt(int x) is a method of the String class - namely it is a function, and you can't assign a function a value in Java.
If you want to loop through a string character by character, I might be tempted to do this:
Char[] GuessAsChar = guess.toCharArray();
Then operate on GuessAsChar instead. There are, depending on your needs, possibly better (as in neater) ways to approach searching for character equivalence in strings.
Not exactly sure what the intention is for guess.equals(word.charAt(i)) as that statement will always evaluate to false since a String never can equal a char, but you want to convert your String to a StringBuilder
private String kNow(String state, String guess) {
final StringBuilder mutable = new StringBuilder(state);
for (int i = 0; i < word.length(); i++) {
if (guess.equals(word.charAt(i))) {
mutable.setCharAt(i, word.charAt(i));
}
}
return mutable.toString();
}
Strings in Java are immutable: you can't change string after it's created. It might be better to use byte[] or char[] or collection for state.
Strings are immutable in Java. This means that you cannot change a string object once you have created it. You can however create a new string and then reassign it to the variable.
state = state.substring(0, i) + word.charAt(i) + state.substring(i + 1);
However in this situation I think it would be better to use a mutable type for state such as a character array (char[]). This allows you to modify individual characters directly.
A second problem with your code is that guess should presumably be a char, not a string. Currently your if statement will always return false because an object of type string will never be equal to an object of type char.

Categories

Resources