Adding two numbers inside a string - java

This is my code:
String result = "10+23";
int calculatedResult = Integer.parseInt(result);
Log.e(TAG, String.valueOf(calculatedResult);
It keeps giving an error.

Well, you cant convert String result = "10+23"; to an int because you have a + there. What exactly are you trying to do? If you want to take 2 Strings and get their result, then here's the code:
String a = "10";
String b = "23";
int result = Integer.parseInt(a) + Integer.parseInt(b);
//The sum of the two values as a String
String calculatedResult = String.valueOf(result);
Log.i("Tag", calculatedResult); //Outputs 33

It give error because "10+23" is not a number it's contains a the symbol + and the method Integer.parseInt(String s); only convert strings like "23" or "10.5"
So to solve the problem try to convert etch number alone, like that
String number1 = "10";
String number2 = "23";
int calculatedResult = Integer.parseInt(number1)+Integer.parseInt(number2);
Log.e(TAG, String.valueOf(calculatedResult);
for more information and examples about Integer.parseInt(String s); click here

Related

How to Parse String.format added 0's to int

I want to generate random national identification number and when i add 0's with String.format() to fill in digits, i can't parse it back into int
public class NinGenerator {
public static void Generator(sex name){ // sex is enum
Random rand = new Random();
int year = rand.nextInt(60) + 40; // For starting at year 40
int month, day, finalNumbers;
month = rand.nextInt(12) + 1;
if(name == sex.FEMALE){ // In case of female
month += 50;
}
switch(month){ // For max number of days to match given month
```
case 1:
case 3:
day = rand.nextInt(30) + 1;
```
}
finalNumbers = rand.nextInt(9999) + 1; // last set of numbers
String nin = FillZeroes(year, 2) + FillZeroes(month, 2) + FillZeroes(day, 2) + FillZeroes(finalNumbers, 4); // Merging it into string
// Here occurs error
int ninInt = Integer.parseInt(nin); // Parsing it into number
while(ninInt % 11 != 0){ // Whole number has to be divisble by 11 without remainder
ninInt++;
}
System.out.println("National identification number: " + ninInt);
}
public static String FillZeroes(int number, int digits){ // For number to correspond with number of digits - filling int with zeros
String text = String.valueOf(number);
if(text.length() < digits){
while(text.length() != digits){
text = String.format("%d1", number);
}
}
return text;
}
}
I want to generate 10 digit number divisible by 11 without reminder, compiler always generates error on the line with parsing
I tested out your code and I believe you are hitting the limit for how high an int can go. If you try placing "2147483647" as your nin value it will run, but as soon as you go to "2147483648" you will get the same error. If you want to fix this you might have to use a datatype such as a long or double depending on what you want to do with it.
Here is a link showing the different datatypes and their ranges.
Your FillZeroes() function could simply be:
public static String FillZeroes(int number, int digits)
{
String format = "d" + digits.ToString();
return number.ToString(format);
}

Sum 2 string numbers [duplicate]

This question already has answers here:
How can I find the sum of two numbers which are in String variables?
(10 answers)
Closed 4 years ago.
I've looked it up, but couldn't get a real answer to that. So I want to know how to sum up 2 string numbers together.
for example:
String a = "8";
String b = "1";
I want to sum both of them to "9". Is that possible?
Thanks.
edit - that is the code Im trying to use:
String num = Integer.toString(i);
String doubleNumber = Integer.toString(i * i);
int length = doubleNumber.length();
String firstNumber;
String secondNumber;
for (int q = 0; q < length; q++) {
firstNumber = doubleNumber.substring(0, Math.min(doubleNumber.length(), q+1));
secondNumber = doubleNumber.substring(q+1, Math.min(doubleNumber.length(), doubleNumber.length()));
String result = String.valueOf(Integer.parseInt(firstNumber) + Integer.parseInt(secondNumber));
if(num.equals(result)) {
isKaprekar = true;
}
}
edit 2 - I have no idea how, but I opened another class, pasted the same code, and it just magically worked. It makes 0 sense, cause its the same project, everything is the same, but it works now, so I don't care. Thanks everyone for the help!
There is a method called Integer#parseInt(String) which returns an int representation of a given String (if possible):
String a = "8";
String b = "1";
int sum = Integer.parseInt(a) + Integer.parseInt(b);
If you want to change it back to a String, use String#valueOf(int):
String s = String.valueOf(sum);
I'd parse them to ints, add them, and then convert the result back to a string:
String result = String.valueOf(Integer.parseInt(a) + Integer.parseInt(b));
You need to convert both to Integers:
String a = "8";
String b = "1";
int sum = Integer.parseInt(a, 10) + Integer.parseInt(b, 10);
The second argument of Integer.parseInt() is the radix, which tells which number base to use. You can leave this argument out altogether and it will default to using a radix of 10:
int sum = Integer.parseInt(a) + Integer.parseInt(b);
If you want to convert them back to a string, just pass the value into String.valueOf():
String sumString = String.valueOf(sum);
Do this:
String a = "8";
String b = "1";
String sum = String.valueOf(Integer.parseInt(a)
+Integer.parseInt(b));
//printing sum
System.out.println(sum);
Parse the string to int using Integer.parseInt(string)and add them as normal integers.
For example :
String result = String.valueOf(Integer.parseInt(a) + Integer.parseInt(b));
should give you the desired string value as "9"

Know the number in a determinate position from a String - Java

I'm getting a number from an addition of Int and then put it as String. I need to know what is the first, second etc. number of the addition. For example the number is 7654, how to know that "7" is the first number? And "6" the second? etc.
String result += "\nThe result of addition"
+ String.valueOf(add_1) + "+" + String.valueOf(add_2)
"+ is" + String.valueOf(int_result);
I want to know the number of a determinate position of the String that contain the result.
The string is String.valueOf(int_result), I can use directly int_result too.
Thanks!
Just walk each character in the resulting string:
String result = String.valueOf(int_result);
for (int i=0; i< result.length(); i++) {
char c = result.charAt(i);
System.out.println("Digit " + i + " = " + c);
// And if you need this as an integer
int digit = Integer.parseInt(""+c);
}
In Java to get the character at a particular position in a string just use this
String number ="7564";
char c = number.charAt(0);
The above code will asign '5' to char variable c. You can further parse it to integer by doing this
int i = Integer.parseInt(c);

Remove unnecessary decimals

I got this code that fetches floats from a database.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += String.valueOf(ing.getAmount()) + " " +
ing.getUnit() + " " + ing.getIngredient() + "\n";
}
The database is written in REAL values as some of them is 1.5, 2.5, 1.4 etc. But we also have these whole numbers without the need of a decimal, such as 1, 4, 10 etc.
The problem is that the database table needs to be in REAL value, which gives us no choice but to give all the values one decimal, no matter if it's needed or not.
So we'll end up with values like:
1.0
1.5
2.3
20.0
5.0
My question is: How do we remove the unnecessary decimals, but keep the ones that need it?
One very simple way to remove these would be to strip the characters using StringUtils.
String displayValue = String.valueOf(ing.getAmount());
displayValue = StringUtils.stripEnd(displayValue, ".0");
For an input of "1.0", "1" will be returned.
A more technical approach would be to use the modulus operator %
For example:
if(value%1 == 0){ //1 divides into number perfectly, there is no decimal
//cast value to integer or another non decimal variable
} else {
//use existing value as it contains a decimal
}
How about this (does't require any fancy things like StringUtils)?
String s = String.valueOf(1.0);
System.out.println(s);
/* Make this block as a function and return an int */
String ss = " ";
if (s.charAt(s.length()-2) == '.' && s.charAt(s.length()-1) == '0'){
ss = s.substring(0,s.length()-2);
System.out.println(ss);
}
/**************************************************/
int converted = Integer.parseInt(ss);
System.out.println(converted);
}
If you want to make it a function block, you can.
You can check it working on IDEONE - http://ideone.com/udJv8M
Check the float values with modulo. If 0 is returned it is an Integer. Here is an example with the numbers you have mentioned:
List<Float> values = new ArrayList<Float>();
values.add(new Float(1.0f));
values.add(new Float(1.5f));
values.add(new Float(2.3f));
values.add(new Float(20.0f));
values.add(new Float(5.0f));
List<String> strValues = new ArrayList<String>();
for(Float value : values)
{
String strValue = "";
if(value % 1 == 0)
{
Integer intValue = value.intValue();
strValue = intValue.toString();
strValues.add(strValue);
}
else
{
strValue = value.toString();
strValues.add(strValue);
}
System.out.println(strValue);
}
You can use a custom DecimalFormat pattern:
public static String customFormat(String pattern, double value) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
return myFormatter.format(value);
}
Then a pattern of # defines places holders for optional digits, so #.### will give up to 3 digits where necessary only.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += customFormat("#.###", ing.getAmount()) +
" " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
So don't convert your data to a String except for display only. Real numbers can represent both integers and floating point numbers using the same data type. Plus if you ever needed to do any math on your numbers you can't use Strings to do that. If you convert your numbers from the database directly to String before storing them into Ingredient then you've screwed yourself later on if you want to do calculations on those numbers. (Say you wanted to add a feature to double a recipe and have all of the quantities change for the user). Under your current plan you're preventing yourself from doing something like that because you're overly focused on the display of that number.
Instead just create a method on Ingredient to convert your numbers using String.format(). Like so:
public class Ingredient {
private double amount;
private String name;
public String asDecimal() {
return String.format("%.1f", amount);
}
public String asInteger() {
return String.format("%.0f", amount);
}
public String asFraction() {
// exercise left to the reader
}
}
You could even add a function that converts decimals to fractional amounts to make it easier to display things chiefs might understand vs decimals which are harder. Bear in mind String.format() will round floating point amounts (0.5 -> 1 using as Integer).
Convert your String returned from ing.getAmount() to a Float object, then use the modulo function to determine whether your value is an exact multiple of 1 (ie no decimal places). If so, convert your Float object to an int, which will concatenate the decimals.
Float f = Float.valueOf(ing.getAmount());
if(f%1 == 0) {
// Use f.intValue() to concatenate your decimals.
ingredients +=String.valueOf(f.intValue() + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
else {
ingredients +=String.valueOf(ing.getAmount()) + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
I hope this helps.

Multiplying with a string in java

I have a string and want to multiply that string by .174.
I have String strNumber = numberText.getText();. How to I proceed from here?
Convert the string to whatever number datatype is appropriate (long if a big number, float/double for decimals etc.) using Long.parseLong(String) or Integer.parseInteger(String) etc. Then you can simply multiply the two numbers.
Example:
String string1 = ".5";//Double in a string
String string2 = "6"; //Integer in a string
double multiplied = Double.parseDouble(string1) * Integer.parseInt(string2) * 3; //.5 * 6 * 3 = 9.0; number form (not string)
Before you can do anything with the number, you have to convert the value to an floating-point value. You can use the following approach:
double num = Double.parseDouble(numberText.getText())
Then you can perform your multiplication.
This might help.
String strNumber = numberText.getText();;
if (strNumber.contains(".")) {
System.out.println(Double.parseDouble(strNumber) * 174);
} else {
System.out.println(Integer.parseInt(strNumber) * 174);
}

Categories

Resources