I need to extract a char from a preset string. I know the method string.charAt(), I use it but it crash my program. The context that I use is the following :
private String values = "0123456789ABCDEFG";
//Converts a 10 base number to a q base
private String t2q(String number, String base) {
String a = Double.toString((int)(Double.parseDouble(number) / Double.parseDouble(base)));
String b = Double.toString((int)(Double.parseDouble(number) % Double.parseDouble(base)));
StringBuilder converted = new StringBuilder(a + b);
if (!check_base(converted.toString(), base)) {
return t2q(a, base) + values.charAt(Integer.parseInt(b));
}
char ab = values.charAt(Integer.parseInt(a));
char ba = values.charAt(Integer.parseInt(b));
return "" + ab + ba;
}
At the beginning i was thinking that my program crash because a is in a Double format e.g 1.0 so i use a function that transforms 1.0 in 1 but nothing, it still crashes. Also i tried with Character instead of char but it doesn't make a difference.
The Exception Error is "java.lang.NumberFormatException: Invalid int : "1.0"" for the example number = "11011" and base = 16 , so 11011 in base 16 is 1B.
You can't parse a String which represents a Double with Integer.parseInt().
This will not work:
Integer.parseInt("3.0");
This will work:
Integer.parseInt("3");
Use this instead:
new Double("3.0").intValue()
But consider following behavior:
new Double("2.5").intValue() will return 2.
Related
Below is the method I am using to generate a string reference id which is of length 12 and starts with 'X' and ends with the input number and the middle of String is filled with zeros
public String generateRefId(Long number){
int digits = 1 + (int)Math.floor(Math.log10(number));
int length = 11 - digits;
StringBuilder refid = new StringBuilder(12);
refid.append('X');
for(int i= length;i> 0;i--) {
refid.append('0');
}
refid.append(number);
Assert.assertEquals(refid.length(),12);
return refid.toString();
}
Below are the usecases
Input Output
12345 X00000012345
999999999 X00999999999
The above method works fine but Am wondering if the above method can be optimized further using java 8?
You can use String.format. E.g.
String.format("X%011d", 4366)
This pads the number with 0 on the left side. But be aware, that larger numbers, will take more space.
groovy:000> String.format("X%011d", 4366)
===> X00000004366
groovy:000> String.format("X%011d", 111111111111)
===> X111111111111
IFF guava is an option, this would be so much easier:
String input = "12345";
System.out.println("X" + Strings.padStart(input, 11, '0'));
In Groovy, since 1.0:
'X' + input.padLeft(11, '0')
As alternative, apache-commons-lang provides the StringUtils.leftPad() method :
public static String leftPad(final String str, final int size, final char padChar)
You could so write :
String input = "999999999";
String formatedValue = "X" + StringUtils.leftPad(input, 11, '0');
I am getting a decimal value in String format from another system
String value = "33.123456".
How can i convert it into the 33123456 , without doing String Split for "[.]" and join it again ?
by replacing . to empty String and parsing it to long
Long.parseLong(value.replace(".", ""));
also handle NumberFormatException
if you want to handle
123.00
to make it like
123
then multiply it with power of 10 as shown below,
String str = "123.0";
int numberOfDigitAfterDecimalPoint = str.length() - str.indexOf(".") - 1;
System.out.println(numberOfDigitAfterDecimalPoint);
System.out.println((long)(Double.parseDouble(str) * Math.pow(10.0, numberOfDigitAfterDecimalPoint - 1)));
or do string operation to check if all the digits are 0 after . then do substring() and Long.parseLong()
double value_double = Double.parseDouble(value.replace('.', ''));
Refer to the Documentation below:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
I have a String s = "abcd" and I want to make a separate String c that is let's say the two first characters of String s. I use:
String s = "abcd";
int i = 0;
String c = s.charAt(i) + s.charAt(i+1);
System.out.println("New string is: " + c);
But that gives error: incompatible types. What should I do?
You should concatenate two Strings and not chars. See String#charAt, it returns a char. So your code is equivalent to:
String c = 97 + 98; //ASCII values for 'a' and 'b'
Why? See the JLS - 5.6.2. Binary Numeric Promotion.
You should do:
String c = String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1));
After you've understood your problem, a better solution would be:
String c = s.substring(0,2)
More reading:
ASCII table
Worth knowing - StringBuilder
String#substring
What you should do is
String c = s.substring(0, 2);
Now why doesn't your code work? Because you're adding two char values, and integer addition is used to do that. The result is thus an integer, which can't be assigned to a String variable.
String s = "abcd";
First two characters of the String s
String firstTwoCharacter = s.substring(0, 2);
or
char c[] = s.toCharArray();
//Note that this method simply returns a call to String.valueOf(char)
String firstTwoCharacter = Character.toString(c[0])+Character.toString(c[1]);
or
String firstTwoCharacter = String.valueOf(c[0])+ String.valueOf(c[1]);
I am trying to convert a hex string to a decimal value (integer). Having found
int i = Integer.valueOf(s, 16).intValue();
here,
i achieved to convert a hex string up to a certain size to an int.
But when the string gets larger, then the int or long does not work, so i tried BigInteger.
Unfortunately, it returns an error :
JEncrytion.java:186: <identifier> expected
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
JEncrytion.java:186: illegal start of expression
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
JEncrytion.java:186: not a statement
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
The code fragment is :
String[] parts = final_key.split("#") ;
String part_fixed = parts[0];
String part_user = parts[1];
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
System.out.println("");
System.out.println("hex value of the key : " + part_user_hex);
Any ideas what to do?
3 errors
You're trying to assign a primitive int value to a BigInteger reference variable. That won't work. You want to do
BigInteger hex = new BigInteger("45ffaaaaa", 16);
Also, you've named your class JEncrytion instead of JEncryption.
Can any one give me some predefined methods or user defined methods to convert string numbers(example: 123455) to comma separated integer value (example: 1,23,455).
int someNumber = 123456;
NumberFormat nf = NumberFormat.getInstance();
nf.format(someNumber);
use java.text.NumberFormat, this will solve your problem.
Finally I found an exact solution for my needs.
import java.math.*;
import java.text.*;
import java.util.*;
public class Mortgage2 {
public static void main(String[] args) {
BigDecimal payment = new BigDecimal("1115.37");
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double doublePayment = payment.doubleValue();
String s = n.format(doublePayment);
System.out.println(s);
}
}
I assume 123455 is a String.
String s = 123455;
String s1 = s.substring( 0 , 1 ); // s1 = 1
String s2 = s.substring( 1 , 3 ); // s2 = 23
String s3 = s.substring( 2 , 7 ); // s3 = 455
s1 = s1 + ',';
s2 = s2 + ',';
s = s1 + s2; // s is a String equivalent to 1,23,455
Now we use static int parseInt(String str) method to convert String into integer.This method returns the integer equivalent of the number contained in the String specified by str using radix 10.
Here you cannot convert s ---> int . Since int does not have commas.If you try to convert you will get the following exception java.lang.NumberFormatException
you should use DecimalFormat Class. http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html
What you're looking for is the DecimalFormat class (here), where you can set easily separator and convert a String to a Number with the method parse() for example.
The result you expected that is "to comma separated integer value", is in my opinion incorrect. However, if you are just looking for output representation, how about these lines of codes shown below? (Note, you can not parse the value return from valueToString to some data type long because it just does not make sense :) )
MaskFormatter format = new MaskFormatter("#,##,###");
format.setValueContainsLiteralCharacters(false);
System.out.println(format.valueToString(123455));