select positions of value of string or int - java

I'm trying to select the positions of some value and print the parts of that value by position in java when I'm working on android app.
for example if I have some number four-digit, 4375 if I select the 3rd one system will print 7, 4th one system will print 5..

You can easily select the portion of a string with String.substring() methods.
See https://docs.oracle.com/javase/7/docs/api/java/lang/String.html for more help.
Hence, you could simply convert the digit to String and then use the substring() method get the part you want.
I will just provide my solution as a suggestion:
private String getSubDigit(int value, int postion){
// you probably should check if the value is correct and ready to be processed.
if(Check(value)) {
String temp = "" + value;
return temp.substring(position,position+1);
}else{
return "";
}
}

You can acheive it like this
int values = 4375;
String mValue = String.valuOf(values);
Char mChar = mValue.chatAt(int index);
int selectedValue = Character.getNumericValue(mChar);

Related

String Cannot Be Converted To Int

This is just a little bit of my code, but I am trying to loop through two strings, get the value of the first number in one string, and then use that number as the position to find in the other string, then add that word into a new string. But it comes up with the error "String cannot be converted to int" can anyone help?
String result = "";
for (int i = 0; i < wordPositions.length; i++){
result += singleWords[wordPositions[i]];
}
if your wordPositions is a String array when you do this:
result += singleWords[wordPositions[i]];
it like if you does this
result += singleWords["value of the wordPositions array at index i"];
but is need to be an int in [] not a string that why you have the exception String can not be cast to Int
If wordPositions is an array of numbers inside a string for example
String[] wordPositions = new String[]{"1","2","3"};
Then you nees to use
Integer.parseInt(NUMBER_IN_STRING);
To change the string value to an int value.
You are getting this error because wordPositions[i] returns a string and you need to convert it to int before trying to acess singlewords[].
result += singleWords[Integer.parseInt(wordPositions[i])];
Use this to convert String into int
Integer.parseInt(integerString);
The completed line of code:
result += singleWords[Integer.parseInt(wordPositions[i])];

Passing returned variable to other method

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.

Making a substring out of a line read from file

So I am trying to read through a .txt file and find all instances of html tags, push opening tags to a stack, and then pop it when I find a closing tag. Right now I am getting String out of bounds exception for the following line:
if(scan.next().startsWith("</", 1))
{
toCompare = scan.next().substring(scan.next().indexOf('<'+2), scan.next().indexOf('>'));
tempString = htmlTag.pop();
if(!tempString.equals(toCompare))
{
isBalanced = false;
}
}
else if(scan.next().startsWith("<"))
{
tempString = scan.next().substring(scan.next().indexOf('<'+1), scan.next().indexOf('>'));
htmlTag.push(tempString);
}
It is telling me that the index of the last letter is -1. The problem I can think of is that all of the scan.next() calls are moving onto the next string. If this is the case, do I need to just write
toCompare = scan.next()
and then so my comparisons?
You have two major problems in your code:
you're calling scan.next() way too much and as you expect, this will move the scanner to the next token. Therefore, the last one will be lost and gone.
.indexOf('<'+2) doesn't return the index of '<' and adds 2 to that position, it will return the index of '>', because you're adding 2 to the int value of char < (60; > has 62). Your problem with index -1 ("It is telling me that the index of the last letter is -1.") comes from this call: .indexOf('<'+1) this looks for char '=' and if your string doesn't contain that, then it will return -1. A call for #substring(int, int) will fail if you pass -1 as the starting position.
I suggest the following two methods to extract the value between '<' and '>':
public String extract(final String str) {
if (str.startsWith("</")) {
return extract(str, 2);
} else if (str.startsWith("<")) {
return extract(str, 1);
}
return str;
}
private String extract(final String str, final int offset) {
return str.substring(str.indexOf('<') + offset, str.lastIndexOf('>'));
}
As you can see, the first method evaluates the correct offset for the second method to cut off either "offset. Mind that I wrote str.indexOf('<') + offset which behaves differently, than your str.indexOf('<' + offset).
To fix your first problem, store the result of scan.next() and replace all occurrences with that temporary string:
final String token = scan.next();
if (token.startsWith("</")) { // removed the second argument
final String currentTag = extract(token); // renamed variable
final String lastTag = htmlTag.pop(); // introduced a new temporary variable
if (!lastTag.equals(currentTag)) {
isBalanced = false;
}
}
else if (token.startsWith("<")) {
htmlTag.push(extract(token)); // no need for a variable here
}
I guess this should help you to fix your problems. You can also improve that code a little bit more, for example try to avoid calling #startsWith("</") and #startsWith("<") twice.

Is there such thing as math.substring in java?

Okay, I'm just getting curious. But I was wondering if there was such thing as a substring for numbers (math.substring ?), and then it would get the character(s) in the position specified.
Example (really poorly thought out one)
int number = 5839;
int example = number.substring(0,1)
println = example;
and then it displays 5?
Why don't you just convert it to a string, and then call substring(0,1)?...
int number = 5839;
int example = Integer.parseInt((number+"").substring(0,1));
Where calling number+"" causes the JVM to convert it into a String, and then it calls substring() on it. You then finally parse it back into an int
int number = 5839;
String numString = Integer.toString(number);
String example = numString.substring(0,1)
int subNum = Integer.parseInt(example);
System.out.println(subNum);
Change it to a String first.
Here's a little function I wrote:
public static int intSubstring(int number, int beginIndex, int endIndex) {
String numString = Integer.toString(number);
String example = numString.substring(beginIndex,endIndex)
int subNum = Integer.parseInt(example);
return subNum;
}
Or compressed:
public static int intSubstring(int number, int beginIndex, int endIndex) {
return Integer.parseInt((number+"").substring(beginIndex,endIndex));
}
No there is not. But you could possibly convert the integer to string and get the substring and again parse back to integer
No there no such thing, but you can do the following:
String s = ""+number; //You can now use the Substring method on s;
Or if you just want to remove the last y digits:
number = (int)(number/y);
of if you want to keep only the last z digits:
number = number%(Math.pow(10,z)); // % means modulo
No, there is none. int is a primitive data type. You can however, accomplish your need with one statement.
Integer.parseInt(String.valueOf(12345).substring(1, 2))

Why is the size of this vector 1?

When I use System.out.println to show the size of a vector after calling the following method then it shows 1 although it should show 2 because the String parameter is "7455573;photo41.png;photo42.png" .
private void getIdClientAndPhotonames(String csvClientPhotos)
{
Vector vListPhotosOfClient = new Vector();
String chainePhotos = "";
String photoName = "";
String photoDirectory = new String(csvClientPhotos.substring(0, csvClientPhotos.indexOf(';')));
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';')+1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
if (chainePhotos.indexOf(';') == -1)
{
vListPhotosOfClient.addElement(new String(chainePhotos));
}
else // aaa;bbb;...
{
for (int i = 0 ; i < chainePhotos.length() ; i++)
{
if (chainePhotos.charAt(i) == ';')
{
vListPhotosOfClient.addElement(new String(photoName));
photoName = "";
continue;
}
photoName = photoName.concat(String.valueOf(chainePhotos.charAt(i)));
}
}
}
So the vector should contain the two String photo41.png and photo42.png , but when I print the vector content I get only photo41.png.
So what is wrong in my code ?
The answer is not valid for this question anymore, because it has been retagged to java-me. Still true if it was Java (like in the beginning): use String#split if you need to handle csv files.
It's be far easier to split the string:
String[] parts = csvClientPhotos.split(";");
This will give a string array:
{"7455573","photo41.png","photo42.png"}
Then you'd simply copy parts[1] and parts[2] to your vector.
You have two immediate problems.
The first is with your initial manipulation of the string. The two lines:
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';')+1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
when applied to 7455573;photo41.png;photo42.png will end up giving you photo41.png.
That's because the first line removes everything up to the first ; (7455573;) and the second strips off everything from the final ; onwards (;photo42.png). If your intent is to just get rid of the 7455573; bit, you don't need the second line.
Note that fixing this issue alone will not solve all your ills, you still need one more change.
Even though your input string (to the loop) is the correct photo41.png;photo42.png, you still only add an item to the vector each time you encounter a delimiting ;. There is no such delimiter at the end of that string, meaning that the final item won't be added.
You can fix this by putting the following immediately after the for loop:
if (! photoName.equals(""))
vListPhotosOfClient.addElement(new String(photoName));
which will catch the case of the final name not being terminated with the ;.
These two lines are the problem:
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';') + 1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
After the first one the chainePhotos contains "photo41.png;photo42.png", but the second one makes it photo41.png - which trigers the if an ends the method with only one element in the vector.
EDITED: what a mess.
I ran it with correct input (as provided by the OP) and made a comment above.
I then fixed it as suggested above, while accidently changing the input to 7455573;photo41.png;photo42.png; which worked, but is probably incorrect and doesn't match the explanation above input-wise.
I wish someone would un-answer this.
You can split the string manually. If the string having the ; symbol means why you can do like this? just do like this,
private void getIdClientAndPhotonames(String csvClientPhotos)
{
Vector vListPhotosOfClient = split(csvClientPhotos);
}
private vector split(String original) {
Vector nodes = new Vector();
String separator = ";";
// Parse nodes into vector
int index = original.indexOf(separator);
while(index>=0) {
nodes.addElement( original.substring(0, index) );
original = original.substring(index+separator.length());
index = original.indexOf(separator);
}
// Get the last node
nodes.addElement( original );
return nodes;
}

Categories

Resources