Know the number in a determinate position from a String - Java - 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);

Related

How to split a string into 2 equal parts in Java

I want to divide a string like this:
String = "Titanic";
into two strings of equal length, and if it isn't divisible by 2 it will have 1 letter or extra on first or second part. like this
//if dividle by 2
Str1 = "BikG";
Str2 = "amer";
//if it isnt dividle by 2
Str1 = "Tita";
Str2 = "nic";
You can do it for example like this:
String base = "somestring";
int half = base.length() % 2 == 0 ? base.length()/2 : base.length()/2 + 1;
String first = base.substring(0, half);
String second = base.substring(half);
Simply when n is the string's length, if n is divisible by 2, split the string in n/2, otherwise split in n/2 + 1 so that first substring is one character longer than second.
What do you do to divide an odd number e.g. 15 with the same requirement?
You store the result of 15 / 2 into an int variable say
int half = 15 / 2
which gives you 7. As per your requirement, you need to add 1 to half to make the first half (i.e. 8) and the remaining half will be 15 - 8 = 7.
On the other hand, in case of an even number, you simply divide it by 2 to have two halves.
You have to apply the same logic in the case of a String as well. Given below is a demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int half;
String str1 = "Titanic";
half = str1.length() / 2;
String str1Part1 = str1.substring(0, half + 1);
String str1Part2 = str1.substring(half + 1);
System.out.println(str1Part1 + ", " + str1Part2);
String str2 = "HelloWorld";
half = str2.length() / 2;
String str2Part1 = str2.substring(0, half);
String str2Part2 = str2.substring(half);
System.out.println(str2Part1 + ", " + str2Part2);
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a string: ");
String str = in.nextLine();
half = str.length() / 2;
System.out.println(str.length() % 2 == 1 ? str.substring(0, half + 1) + ", " + str.substring(half + 1)
: str.substring(0, half) + ", " + str.substring(half));
System.out.print("Enter Y to continue or any input to exit: ");
} while (in.nextLine().toUpperCase().equals("Y"));
}
}
A sample run:
Tita, nic
Hello, World
Enter a string: Arvind
Arv, ind
Would you like to continue? [Y/N]: y
Enter a string: Kumar
Kum, ar
Would you like to continue? [Y/N]: Y
Enter a string: Avinash
Avin, ash
Would you like to continue? [Y/N]: n
Note:
% is a modulo operator.
Check String substring​(int beginIndex, int endIndex) and String substring​(int beginIndex) to learn more about substring functions of String.
Check https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html to learn about the ternary operator.
You could use String.substring() for this purpose:
String s = "Titanic";
int half = (s.length()+1)/2;
String part1 = s.substring(0, half);
String part2 = s.substring(half);
System.out.println(part1); // Prints: Tita
System.out.println(part2); // Prints: nic
Here (s.length()+1)/2 will auto-truncate 0.5 if it occurs because the division is between ints.

Random negative number when converting numbers from string to int in Java

Attempting to convert string of numbers to binary with this code
public static int convert(String text)
{
int num =0;
for(int i =0; i<text.length();i++)
{
if(((int)text.charAt(i)>=48)&&((int)text.charAt(i)<=59))
{
System.out.println("Before: i = " + i + " num = "+ num+" char = "+ text.charAt(i) + "numchar = " + ((int)text.charAt(i)-48));
num = num*10 + ((int)text.charAt(i)-48);
System.out.println("After: i = " + i + " num = "+ num+" char = "+ text.charAt(i) + "numchar = " + ((int)text.charAt(i)-48));
}
}
return num;
}
}
However once it reaches its 10th number the output becomes a complete jumble with negative numbers and random numbers, even when my test strings are binary. Any idea why this could be happening?
The int datatype in Java is a 32-bit signed integer, so the maximum value it can represent is 2^31 - 1 = 2147483647. Since you are trying to parse numbers bigger than this, your arithmetic will result in integer overflow.
To solve this problem you will need to use a datatype which can represent larger integers, such as long (up to about 19 digits) or BigInteger (arbitrarily large).

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"

Java: Finding Percent Difference

I am trying to figure out how to find the percent difference between the original (no space) string of text and the disemvoweled (no space) string of text. I am attempting to do this by using the equation ((newAmount-reducedAmount)/reducedAmount) but I am having no luck and am ending up with a value of zero, as shown below.
Thank you!
My Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
System.out.println("Welcome to the disemvoweling utility!"); // Initially typed "disemboweling" xD
System.out.print("Enter text to be disemvoweled: ");
String inLine = console.nextLine();
String vowels= inLine.replaceAll("[AEIOUaeiou]", ""); // RegEx for vowel control
System.out.println("Your disemvoweled text is: " + vowels); // Prints disemvoweled text
// Used to count all characters without counting white space(s)
int reducedAmount = 0;
for (int i = 0, length = inLine.length(); i < length; i++) {
if (inLine.charAt(i) != ' ') {
reducedAmount++;
}
}
// newAmount is the number of characters on the disemvoweled text without counting white space(s)
int newAmount = 0;
for (int i = 0, length = vowels.length(); i < length; i++) {
if (vowels.charAt(i) != ' ') {
newAmount++;
}
}
int reductionRate = ((newAmount - reducedAmount) / reducedAmount); // Percentage of character reduction
System.out.print("Reduced from " + reducedAmount + " to " + newAmount + ". Reduction rate is " + reductionRate + "%");
}
}
My output: (Test string is without quotes: "Testing please")
Welcome to the disemvoweling utility!
Enter text to be disemvoweled: Testing please
Your disemvoweled text is: Tstng pls
Reduced from 13 to 8. Reduction rate is 0%
You used an integer data type while calculating percentage difference while performing integer division. You need to type cast one of the variables on the right hand side of the equation to perform double division and then store them in double. The reason for doing this is java integer type can't hold the real numbers.
Also, multiple it by 100 to get the percentage.
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);
If you want a fraction between 0 and 1, then
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);
Your formula gives you a value between zero and one.
An integer cannot hold fractions so it always shows zero.
Multiply by 100 to get a regular percentage value.
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reduction

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.

Categories

Resources