I want to display the length of a 4-digit number displayed by the user, the problem that I'm running into is that whenever I read the length of a number that is 4-digits long but has trailing zeros the length comes to the number of digits minus the zeros.
Here is what I tried:
//length of values from number input
int number = 0123;
int length = (int)Math.log10(number) + 1;
This returns to length of 3
The other thing I tried was:
int number = 0123;
int length = String.valueOf(number).length();
This also returned a length of 3.
Are there any alternatives to how I can obtain this length?
Because int number = 0123 is the equivalent of int number = 83 as 0123 is an octal constant. Thanks to #DavidConrad and #DrewKennedy for the octal precision.
Instead declare it as a String if you want to keep the leading 0
String number = "0123";
int length = number.length();
And then when you need the number, simply do Integer.parseInt(number)
Why is the syntax of octal notation in java 0xx ?
Java syntax was designed to be close to that of C, see eg page 20 at
How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008
by James Gosling (20_Gosling_keynote.pdf):
In turn, this is the way how octal constants are defined in C language:
If an integer constant begins with 0x or 0X, it is hexadecimal. If it
begins with the digit 0, it is octal. Otherwise, it is assumed to be
decimal...
Note that this part is a C&P of #gnat answer on programmers.stackexchange.
https://softwareengineering.stackexchange.com/questions/221797/reasoning-behind-the-syntax-of-octal-notation-in-java
Use a string instead:
String number = "0123";
int length = number.length(); // equals 4
This doesn't work with an int, as the internal representation of 0123 is identical to 123. The program doesn't remember how the value was written, only the actual value.
What you can do is declare a string:
String number = "0123";
int numberLengthWithLeadingZeroes = number.length(); // == 4
int numberValue = Integer.parseInt(number); // == 123
If you really want to include leading 0's you could always store it in an array of of characters
example:
char[] abc = String.valueOf(number).toCharArray();
Then obviously you can figure out the length of the array.
As several people have pointed out already though, integers don't have leading 0's.
String abc=String.format("%04d", yournumber);
for zero-padding with length=4.
Refer to this link .
http://download.oracle.com/javase/7/docs/api/java/util/Formatter.html
this might help u ..
Integers in Java don't have leading zeroes. If you assign the value 0123 to your int or Integer variable, it will be interpreted as an octal constant rather than a decimal one, which can lead to subtle bugs.
Instead, if you want to keep leading zeroes, use a String, e.g.
String number = "0123";
This way you can also measure the length:
String number = "0123";
System.out.println(number.length());
Related
I want to create a numerical representation of 5 letter codes. The codes may have 1-5 letters or digits.
The number must of course be unique. It is not absolutely necessairy that those numbers can be converted back to the ascii.
Thus I need digits from 0 to ZZZZZ
The resulting number size should be as small as possible.
I started with the following, but it's not quite what I want:
String a="ZZZZZZ";
for (int i = 0; i < a.length(); ++i) {
System.out.print(a.charAt(i)-'A'+1);
}
ZZZZZZ=262626262626
000000=-16-16-16-16-16-16
Start by enumerating all possible "digits" of your number:
Ten decimal digits 0 through 9
Twenty six letters A through Z
You have 36 possible "digits" for five positions, so the max number is 365=60,466,176. This number fits in an int.
You can make this number by calling Integer.parseInt, and passing a radix of 36:
System.out.println(Integer.parseInt("ABZXY", 36)); // 17355958
Demo.
Keep in mind that A134Z is already a number; it is only printed in Base-36 representation!
Albeit being just one sentence, the above should give you all you need to know to translate any 5-character string with 0-9 and A-Z into a number (and back).
Simplest solution - if letters are case insensitive is to use radix of 36 - full alphabet plus 10 digits. That way you get both functions for free - converting from string to long and from long to string like this:
long numericCode = Long.parseLong("zzzzz", 36); // gives 60466175
String stringCode = Long.toString(numericCode, 36); // gives "zzzzz"
You can treat the string as a number in base36 (where A=10, B=11 ... Z=35). This way, you will use exactly the numbers from 0 to 36^5-1, and each will be used exactly once.
Well, I have a string in my Java code that needs to be converted into an integer with padding of 10.
Ex. Consider this is the string... Str = "52112"
I need to convert this string into an integer and the result should be like "0000052112". The result should be an integer. Can anyone help me with this, please?
As far as I know you cannot have an integer typed variable with leading zeros. You can pad the number with zeros but then it will become a String.
Take a look at:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#leftPad(java.lang.String,%20int)
In order to conform to the signature you have to convert the number to a string first, but that is no great deal.
The leading zeroes have no meaning if the data type you require is an Integer (or any other numeric type). If on the other hand you need a String with leading zeroes, you can use this (works only if required string length is >= number of digits of the number you want to pad) :
String myNumber = Integer.toString(42);
String myNumberWithLeadingZeroes = "0000000000" + myNumber;
// 10 zeroes if you need a string of length 10 in the end
myNumberWithLeadingZeroes = myNumberWithLeadingZeroes.substring(myNumber.length());
I am trying to get a char from an int value > 0xFFFF. But instead, I always get back the same char value, that when cast to an int, prints the value 65535 (0xFFFF).
I couldn't understand why it is generating symbols for unicode > 0xFFFF.
int hex = 0x10FFFF;
char c = (char)hex;
System.out.println((int)c);
I expected the output to be 0x10FFFF. Instead, the output comes back as 65535.
This is because, while an int is 4 bytes, a char is only 2 bytes. Thus, you can't represent all values in a char that you can in an int. Using a standard unsigned integer representation, you can only represent the range of values from 0 to 2^16 - 1 == 65535 in a 2-byte value, so if you convert any number outside that range to a 2-byte value and back, you'll lose data.
int is 4 byte. char is 2 byte.
Your number was well within range an int can hold, but not which char can.
So when you converted that number to a char, it lost data and became the maximum a char can hold, which is what it printed i.e. 65535
Your number was too big to be a char which is 2 bytes. But it was small enough where it fit in as an int which is 4 bytes. 65535 is the biggest amount that fits in a char so that's why you got that value. Also, if a char was big enough to fit your number, when you returned it to an int it might have returned the decimal value for 0x10FFFF which is 1114111.
Unfortunately, I think you were expecting a Java char to be the same thing as a Unicode code point. They are not the same thing.
The Java char, as already expressed by other answers, can only support code points that can be represented in 16 bits, whereas Unicode needs 21 bits to support all code points.
In other words, a Java char on its own, only supports Basic Multilingual Plane characters (code points <= 0xFFFF). In Java, if you want to represent a Unicode code point that is in one of the extended planes (code points > 0xFFFF), then you need surrogate characters, or a pair of characters to do that. This is how UTF-16 works. And, internally, this is how Java strings work as well. Just for fun, run the following snippet to see how a single Unicode code point is actually represented by 2 characters if the code point is > 0xFFFF:
// Printing string length for a string with
// a single unicode code point: 0x22BED.
System.out.println("πΆ―".length()); // prints 2, because it uses a surrogate pair.
If you want to safely convert an int value that represents a Unicode code point to a char (or chars to be more exact), and then convert it back to an int code point, you will have to use code like this:
public static void main(String[] args) {
int hex = 0x10FFFF;
System.out.println(Character.isSupplementaryCodePoint(hex)); // prints true because hex > 0xFFFF
char[] surrogateChars = Character.toChars(hex);
int codePointConvertedBack = Character.codePointAt(surrogateChars, 0);
System.out.println(codePointConvertedBack); // prints 1114111
}
Alternatively, instead of manipulating char arrays, you can use a String, like this:
public static void main(String[] args) {
int hex = 0x10FFFF;
System.out.println(Character.isSupplementaryCodePoint(hex)); // prints true because hex > 0xFFFF
String s = new String(new int[] {hex}, 0, 1);
int codePointConvertedBack = s.codePointAt(0);
System.out.println(codePointConvertedBack); // prints 1114111
}
For further reading: Java Character Class
I was playing a bit with numbers, and something interesting came upon me, which I don't quite understand.
public static void main(String[] args) {
int hexNumber = 0x7A;//decimal: 122 binary:0111 1010
int decNumber = 122;
int binNumber = 1111010;
System.out.println(hexNumber);//122
System.out.println(Integer.toString(hexNumber, 16)); //7a
System.out.println(Integer.toHexString(hexNumber)); //7a
System.out.println(Integer.toString(hexNumber, 2)); // 1111010
System.out.println(Integer.toBinaryString(hexNumber)); //1111010
System.out.println(hexNumber==binNumber);//false
System.out.println(hexNumber==decNumber);//true
System.out.println(decNumber==binNumber);//false
}
Why do I get "false" at #1 and #3? Doesn't change even if binNumber = 01111010;
Well, you can't directly store binary values in Java without any prefix.
binNumber isn't stored as the binary number 1111010; instead, it's stored as the decimal number 1111010.
This you have to store as int binNumber = Integer.parseInt("1111010", 2); or better yet int binNumber = 0b1111010;.
For octal:
int octalNo = 0177; //'0' is prefix
or
int octalNo = Integer.parseInt("0177", 8); //leading '0's are ignored
For hexadecimal:
int hexNo = 0x177; //'0x' is prefix
or
int hexNo = Integer.parseInt("0177", 16); //leading '0's are ignored
For more info, have a look at this.
You aren't creating the binary number as a binary one. You are creating it as a decimal one (base 10) that happens to only contain 0s and 1s.
To store 0111 1010 in Java 7 use the new binary literal (you can even use underscores for easier reading)
int binNumber = 0b0111_1010;
Because that's not the proper way to specify the binary number (and there is no such way in Java, apart from something like Integer.toBinaryString(122) which would give you a proper binary representation (returned as a String)).
Your number was interpreted as a "normal" decimal integer (if entered without leading 0) or as an integer in octal system (if entered with leading 0).
In Java versions before 7, you need to use this
int binNumber = Integer.parseInt("1111010", 2);
In 7 and up, you can use
int binNumber = 0b1111010;
With that change, your code works here (I get three true resuls).
The answer is clear. You have assigned to integers some diferent values.hexNumber is initialized to decimal value 122, even if the representation you use for that is hexadecimal. decNumber is initialized to decimal value 122, so when you compare hexNumber and decNumber you will get true because it's really the same value. Finally binNumber is initialized to the decimal value 1111010, so if you compare it with one of the other numbers you will get false.
I can't think of a better way to left pad an integer with zeroes without first converting it to a String. Is there a way to do this? I've found numerous questions regarding this but they all require a String conversion. I understand we can find the length with this approach:
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
However, this will still require me to convert it to a String and back afterwards. Surely, there's a better way?
No. An int represents a mathematical integer value, represented as 32 bits. The number 0001 is 1, and has a unique binary representation. Left-padded integers are not integers. they are Strings.
No. Numeric types cannot contain leading zeros. This a feature of the formatted textual representation i.e. Strings
Since you already have the length I'm guessing the leading zero's are simply for output, but ultimately your question was answered by the other two posters.
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
String zeros;
for(int i=0; i<length; i++) {
zeros = zeros.concat("0");
}
System.out.println(zeros + num);