This is what I have :
final EditText Pikkus = (EditText)findViewById(R.id.editText);
final EditText Laius = (EditText)findViewById(R.id.editText3);
final TextView pindala1 = (TextView)findViewById(R.id.editText2);
final TextView ymbermoot1 = (TextView)findViewById(R.id.textView5);
ImageButton button = (ImageButton)findViewById(R.id.teisenda);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pindala2 = "" + Integer.parseInt(Pikkus.getText().toString()) * Integer.parseInt(Laius.getText().toString());
pindala1.setText(pindala2);
String ymbermoot2 = "" + Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString())
ymbermoot1.setText(ymbermoot2);
}
});
But the
String ymbermoot2 = ""
+ Integer.parseInt(Pikkus.getText().toString())
+ Integer.parseInt(Laius.getText().toString());
ymbermoot1.setText(ymbermoot2);
part doesn't work like its supposed to. Instead of adding up the values, it simply types them together. Example: integer Pikkus is 26, Laius is 23. The value should end up being 49, but my code somehow makes it to up to be 2623. Where's the mistake in the code?
Try something like this.
String ymbermoot2 = Integer.toString(Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString()));
That's what happens when you try to write as little lines as possible, and it's so wrong. Of course - number of lines determines good code but not always. So I would split it into few lines:
int someNumber = Integer.parseInt(Pikkus.getText().toString());
int someOtherNumber = Integer.parseInt(Laius.getText().toString());
String pindala2 = String.valueOf(someNumber * someOtherNumber);
Try the following code:
String ymbermoot2 = "" + (Integer.parseInt(Pikkus.getText().toString())
+ Integer.parseInt(Laius.getText().toString()))
It will help.
String pindala2 = "" + (Integer.parseInt(Pikkus.getText().toString()) * Integer.parseInt(Laius.getText().toString()));
int value = Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString())
This is because you are concatenating strings instead of adding or multiplying them up because you cannot make arithmetic operations on strings . Try following code :
String pindala2 = ""+Integer.toString((Integer.parseInt(Pikkus.getText().toString()) * Integer.parseInt(Laius.getText().toString())));
Here we are first we multiply two integers and then converting it to String.
Related
String can be like below. Using java1.6
String example = "<number>;<name-value>;<name-value>";
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String abc = "+17005554141;qwq=123454";
String abc = "+17005554141";
I want to remove qwq=1234 if present from String. qwq is fixed and its value can VARY like for ex 1234 or 12345 etc
expected result :
String abc = "+17005554141;ddd=ewew;otg=383";
String abc = "+17005554141"; \\removed ;qwq=123454
String abc = "+17005554141";
I tried through
abc = abc.replaceAll(";qwq=.*;", "");
but not working.
I came up with this qwq=\d*\;? and it works. It matches for 0 or more decimals after qwq=. It also has an optional parameter ; since your example seems to include that this is not always appended after the number.
I know the question is not about javascript, but here's an example where you can see the regex working:
const regex = /qwq=\d*\;?/g;
var items = ["+17005554141;qwq=123454",
"+17005554141",
"+17005554141;qwq=1234;ddd=ewew;otg=383"];
for(let i = 0; i < items.length; i++) {
console.log("Item before replace: " + items[i]);
console.log("Item after replace: " + items[i].replace(regex, "") + "\n\n");
}
You can use regex for removing that kind of string like this. Use this code,
String example = "+17005554141;qwq=1234;ddd=ewew;otg=383";
System.out.println("Before: " + example);
System.out.println("After: " + example.replaceAll("qwq=\\d+;?", ""));
This gives following output,
Before: +17005554141;qwq=1234;ddd=ewew;otg=383
After: +17005554141;ddd=ewew;otg=383
.* applies to multi-characters, not limited to digits. Use something that applies only to bunch of digits
abc.replaceAll(";qwq=\\d+", "")
^^
Any Number
please try
abc = abc.replaceAll("qwq=[0-9]*;", "");
If you don't care about too much convenience, you can achieve this by just plain simple String operations (indexOf, replace and substring). This is maybe the most legacy way to do this:
private static String replaceQWQ(String target)
{
if (target.indexOf("qwq=") != -1) {
if (target.indexOf(';', target.indexOf("qwq=")) != -1) {
String replace =
target.substring(target.indexOf("qwq="), target.indexOf(';', target.indexOf("qwq=")) + 1);
target = target.replace(replace, "");
} else {
target = target.substring(0, target.indexOf("qwq=") - 1);
}
}
return target;
}
Small test:
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String def = "+17005554141;qwq=1234";
System.out.println(replaceQWQ(abc));
System.out.println(replaceQWQ(def));
outputs:
+17005554141;ddd=ewew;otg=383
+17005554141
Another one:
abc.replaceAll(";qwq=[^;]*;", ";");
You must to use groups in replaceAll method.
Here is an example:
abc.replaceAll("(.*;)(qwq=\\d*;)(.*)", "$1$3");
More about groups you can find on: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
I need help to parse a string in Java... I'm very new to Java and am not sure how to go about it.
Suppose the string I want to parse is...
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;"
What I would want to do is:
String name = C43
String direction = EB2;
Then what I'd like to do is store 2 coordinates as a pair...
Coordinate c1 = 49.21716;-122.667252;
Coordinate c2 = 49.216757;-122.666235;
And then make a List to store c1 and c2.
So far I have this:
parseOnePattern(String str) {
String toParse = str;
name = toParse.substring(1, toParse.indexOf("-"));
direction = toParse.substring(toParse.indexOf("-", toParse.indexOf(";")));
I'm not sure how to move forward. Any help will be appreciated.
A simple substring function may solve your problem.
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String[]s = str.split(";");
String[]n = s[0].split("-");
String name = n[0].substring(1);
String direction = n[1];
String c1 = s[1] +";"+s[2];
String c2 = s[3] +";"+s[4];
System.out.println(name + " " + direction);
System.out.println(c1 + " " + c2);
I hope this helps you.
Welcome to Java and the whole set of operations it allows to perform on Strings. You have a whole set of operations to perform, I will give you the code to perform some of them and get you started :-
public void breakString() {
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235";
// Will break str to "NC43-EB2" and "49.21716" "-122.667252" "49.216757" "-122.666235"
String [] allValues = str.split(";", -1);
String [] nameValuePair = allValues[0].split("-");
// substring selects only the specified portion of string
String name = nameValuePair[0].substring(1, 4);
// Since "49.21716" is of type String, we may need it to parse it to data type double if we want to do operations like numeric operations
double c1 = 0d;
try {
c1 = Double.parseDouble(allValues[1]);
} catch (NumberFormatException e) {
// TODO: Take corrective measures or simply log the error
}
What I would suggest you is to go through the documentation of String class, learn more about operations like String splitting and converting one data type to another and use an IDE like Eclipse which has very helpful features. Also I haven't tested the code above, so use it as a reference and not as a template.
Ok i made this:
public static void main(String[] args) {
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String[] strSplit = str.split(";");
String[] nameSplit=strSplit[0].split("-");
String name=nameSplit[0].replace("N", "");
String direction= nameSplit[1];
String cordanateOne = strSplit[1]+";"+strSplit[2]+";";
String cordanateTwo = strSplit[3]+";"+strSplit[4]+";";
System.out.println("Name: "+name);
System.out.println("Direction: "+direction);
System.out.println("Cordenate One: "+cordanateOne);
System.out.println("Cordenate Two: "+cordanateTwo);
}
Name: C43
Direction: EB2
Cordenate One: 49.21716;-122.667252;
Cordenate Two: 49.216757;-122.666235;
String str3 = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String sub = str3.substring(0,4); // sub = NC43
String sub4 = str3.substring(5,9); // sub = EB2;
HashMap<String, String> hm = new HashMap<>();
hm.put(str3.substring(9 ,30), str3.substring(30));
hm.forEach((lat, lot) -> {
System.out.println(lat + " - " + lot); // 49.21716;-122.667252; - 49.216757;-122.666235;
});
//edit if using an array non pairs (I assumed it was lat + lon)
List<String> coordList = new ArrayList<>();
coordList.add(str3.substring(9 ,30));
coordList.add(str3.substring(30));
coordList.forEach( coord -> {
System.out.println(coord);
});
//output : 49.21716;-122.667252;
49.216757;-122.666235;
I am writing a program which is the opposite of Auto Correct. The logic is that the user enters a sentence, when a button is pressed, the grammatical opposite of the sentence entered by the user should be displayed. I am roughly able to get the code. I used the matcher logic.But i am not able to get the desired output. I am linking the code with this question. Can anyone help me please?
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = editText.getText().toString();
String store = input;
String store1 [] = store.split(" ");
String correct[] = {"is","shall","this","can","will"};
String wrong [] = {"was","should","that","could","would"};
String output = "";
for (int i=0;i<store1.length;i++) {
for(int j=0;j<correct.length;j++){
if(store1[i].matches(correct[j])) {
output = input.replace(store1[i], wrong[j]);
//store1[i] = wrong[j];
}
else
{
input.replace(store1[i], store1[i]);
//store1[i] = store1[i];
}
}
mTextView.setText(output);
}
}});
By looking at your code, I've found some redundancy and unused variable. Shown as below.
String store = input;
String store1 [] = store.split(" ");
As shown below, I did some cleanup for you and implement your logic using Map interface. The wrong value must be the Key of the map so that we can easily determine is the word a wrong value using Map.containKeys(word). If key is found then we concatenate the output variable with the correct word.
String input = editText.getText().toString().split(" ");
Map<String, String> pairs = new HashMap<>();
pairs.put("is", "was");
pairs.put("shall", "should");
pairs.put("this", "that");
pairs.put("can", "could");
pairs.put("will", "would");
String output = "";
for (String word : input) {
if (pairs.containsKey(word)) {
output = output + pairs.get(word) + " ";
} else {
output = output + word + " ";
}
}
mTextView.setText(output.trim());
I have a string that might look like this:
searchText = search:kind:(reports) unit.id:(("CATS (WILLIAMS)"~1) OR ("DOGS (JAMES)"~1))
I need to extact any values that may exist in the quotation marks so in this case it would be:
CATS (WILLIAMS) and DOGS (JAMES)
Not sure I understand how using indexOf and subString will get me a text string since they depend on integer values... Can someone show me some examples of how this might be done? Thanks
Ok figured out the basics, but I need it to extract every value in " " not just the first instance. The below extacts the value then converts the name into an id then replaces the name with an id, but ONLY does the first instance.
String unitIdStart = "\"";
String unitIdEnd = "\"~";
int unitIdStartIndex = searchText.indexOf(unitIdStart);
if( unitIdStartIndex != -1 ) {
int unitIdEndIndex = searchText.indexOf(unitIdEnd, unitIdStartIndex);
if( unitIdEndIndex != -1 );
{
String unitName = searchText.substring(unitIdStartIndex+1, unitIdEndIndex);
Unit backToId = UnitRepository.getIdFromName(unitName);
String unitId = backToId.getId().toString();
String searchTextWithUnitId = searchText.replace(unitName, unitId);
I have a string String a = "(3e4+2e2)sin(30)"; and i want to show it as a = "(3e4+2e2)*sin(30)";
I am not able to write a regular expression for this.
Try this replaceAll:
a = a.replaceAll("\) *(\\w+)", ")*$1");
You can go with this
String func = "sin";// or any function you want like cos.
String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)]" + func, ")*siz");
System.out.println(a);
this should work
a = a.replaceAll("\\)(\\s)*([^*+/-])", ") * $2");
String input = "(3e4+2e2)sin(30)".replaceAll("(\\(.+?\\))(.+)", "$1*$2"); //(3e4+2e2)*sin(30)
Assuming the characters within the first parenthesis will always be in similar pattern, you can split this string into two at the position where you would like to insert the character and then form the final string by appending the first half of the string, new character and second half of the string.
string a = "(3e4+2e2)sin(30)";
string[] splitArray1 = Regex.Split(a, #"^\(\w+[+]\w+\)");
string[] splitArray2 = Regex.Split(a, #"\w+\([0-9]+\)$");
string updatedInput = splitArray2[0] + "*" + splitArray1[1];
Console.WriteLine("Input = {0} Output = {1}", a, updatedInput);
I did not try but the following should work
String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)](\\w+)", ")*$1");
System.out.println(a);