Adding numbers within a string in java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I add two numbers within one string?
I have:
String a = "(x+x)";
String lb = "2";
String b = a.replace("x", lb);
int c = ?
it outputs 2+2, how do I get it to add them together correctly into an integer?

While you can use a Java library to achieve this goal as mentioned in the comments, there is something built into Java since version 6 which may be useful (but maybe a little overkill). I suggest this not because I believe it's particularly efficient but rather as an alternative to using a library.
Use JavaScript:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
ScriptEngine jsRuntime = new ScriptEngineManager().getEngineByName("javascript");
String expression = "2+2"; //The expression you would to evaluate.
double result = (Double) jsRuntime.eval(expression);

Use the Integer.parseInt method to parse a String into an int, then add the values. Adding strings just concatenates them.

You can use parseInt() method.

It seems your question could be summarised as
How do I convert a String such as "2+2" to the number 4
Here's a solution that uses only the standard Java libraries:
String sumExpression = "2+2";
String[] numbers = sumExpression.split("\\+");
int total = 0;
for (String number: numbers) {
total += Integer.parseInt(number.trim());
}
// check our result
assert total == 4;

Related

Converting string phone number to long: Number Format Exception [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am fairly inexperienced in Java as well as Android. I am trying to retrieve a phone number stored in one of the contacts of the android phone emulator. While I am successful to fetch it, the number has been returned in a string in a format like "(987) 654-3210".
I want to convert it to integer or long. How can I do that? If I use Integer.parseInt(String number), it returns a NumberFormatException. Failed while tried using Long.valueOf(String number) too. What should I do then? I want it like "9876543210" without any braces or hyphens.
using the long for storing number will be better
String str="(987) 654-3210";
String stt=str.replaceAll("\\D+","");
long num= Long.parseLong(stt);
System.out.println(num);
This should be simple. You could use regex in java to do this like below
phoneStr = str.replaceAll("\\D+","");
This will delete the non digits from the string and give you only numbers. Then you can use
int number = Integer.parseInt(phoneStr);

Android converting string to array string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string like this:
["477","com.dummybilling","android.test.purchased","inapp:com.dummybilling:android.test.purchased","779"]
How to have a String[] with these 5 element?
Does anyone know a regex for .split() method?
Thank you very much, regular expressions make me crazy! :(
Process it as JSON. Two immediate benifits would be that it would take care of any embedded commas in your data automatically and the other that you would get a String[] with unquoted strings.
String input = "[\"477\",\"com.dummybilling\",\"android.test.purchased\",\"inapp:com.dummybilling:android.test.purchased\",\"779\"]";
JSONArray jsonArray = new JSONArray(input);
String[] strArr = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
strArr[i] = jsonArray.getString(i);
}
System.out.println(Arrays.toString(strArr));
Output :
[477, com.dummybilling, android.test.purchased, inapp:com.dummybilling:android.test.purchased, 779]
You can split your string by separator [" (the beginning) or "," or "] (the ending) like this:
final String[] tokens = yourString.split("\",\"|\\[\"|\"\\]");
Please note that this will only work for your string. It's not a general solution (for example, it does not take care of any escaped quotes). If your string is in JSON format, you should use a JSON parser as proposed by #Ravi Thapliyal .

How to create random cell number for testing purpose [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to create a random cellnumber 07939393914 for automation testing purpose.
Last 079393(5 digits) digits should change randamly.. each time test runs..
Can any one suggest JAVA code for this ? or else Selenium Java code ?
Thanks
Is this a number or a String? I ask as it has a leading zero.
Take you initial number as 7939300000
then add to it Math.round(Math.Random()*10000)
If you want it as a String, take your string as "079393" and use Integer.toString on the result above, then concatentate them
Use RandomStringUtils class.
String randomNumbers = RandomStringUtils.randomNumeric(5);
String phNo = 079393+randomNumbers;
var num=Math.ceil(Math.Random()*100000)
for random first 5 digit numbers
and add
var your_last_5digits; //as string to your last 5 digits
cellNumber='0'+num+your_last_5digits;

Converting the string phone number to integer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am fairly inexperienced in Java as well as Android. I am trying to retrieve a phone number stored in one of the contacts of the android phone emulator. While I am successful to fetch it, the number has been returned in a string in a format like "(987) 654-3210".
I want to convert it to integer or long. How can I do that? If I use Integer.parseInt(String number), it returns a NumberFormatException. Failed while tried using Long.valueOf(String number) too. What should I do then? I want it like "9876543210" without any braces or hyphens.
using the long for storing number will be better
String str="(987) 654-3210";
String stt=str.replaceAll("\\D+","");
long num= Long.parseLong(stt);
System.out.println(num);
This should be simple. You could use regex in java to do this like below
phoneStr = str.replaceAll("\\D+","");
This will delete the non digits from the string and give you only numbers. Then you can use
int number = Integer.parseInt(phoneStr);

Check if all chars match? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Basically, I have to write a method that determines whether all the characters in a string are the same, using only library String methods.
Use matches. Please read up the documentation of Pattern class to understand how to use matches function to check your input. It is quite useless for me to give you a straight answer, since you don't learn much from it.
That method will give you one-liner solution after you have understood regex.
public static void main(String[] args) {
String str = "aaaaa";
int count = str.length() - str.replaceAll(String.valueOf(str.charAt(0)), "").length();
if(count == str.length())
System.out.println("All characters in a given String are same");
}
Try this : This is the simplest and best solution for this kind of problem.
One way to solve this is without looping or recursion is by [ab]using String.replace1.
The actual implementation is left as an exercise.
1 It does not require that your code loops, but something must loop.

Categories