Calculate number from CharArray - java

I have following code
private static int getYear(char[] charArray)
{
return (int)charArray[0] * 1000 + (int)charArray[1] * 100 + (int)charArray[2] * 10 + (int)charArray[3];
}
This excerpt calculate a number from a 4-element char array. From "2015" there is 55343.
Any suggestion?

Assuming the purpose of the exercise is not to use String and parseInt, you need to convert the characters '0' to '9' into the digits 0 to 9. This is done by subtracting the character '0', so you get:
private static int getYear(char[] charArray)
{
return (charArray[0] - '0') * 1000
+ (charArray[1] - '0') * 100
+ (charArray[2] - '0') * 10
+ (charArray[3] - '0');
}
This is because Java stores Strings in Unicode characters. Unicode is a (huge) extension of the ASCII character set.
Have a look at the ASCII printable characters on this Wikipedia page: https://en.wikipedia.org/wiki/ASCII#ASCII_printable_code_chart
As you can see, the character (glyphs) for 0 has decimal value 48, 1 is 49, ..., and 9 is 57.
So, casting a char with the character '0' to an int will yield the value 48. Then we rely on the fact that the characters '0' to '9' are consecutive, so subtracting 48 (the value of '0') will yield 0 to 9, which is what we want.

private static int getYear(char[] charArray)
{
return Integer.parseInt(String.valueOf(charArray));
}

private static int getYear(char[] charArray){
return Integer.parseInt(new String(charArray));
}

Related

Java conversion to base 7

I have been trying to understand a code of a program that converts decimal to the base of 7. I do understand everything until the point where the given loop begins. Could you explain me that?
do {
char digit = (char) (number % 7 + '0');
s = digit + s;
number /= 7;
} while (number > 0);
System.out.print(s);
From the comments, it seems it is mainly this line
char digit = (char) (number % 7 + '0');
you do not understand.
It converts the value of number % 7, which is an integer, to a digit as a character. The character codes of the digits are successive with 48 for '0', 49 for '1', and so on. Adding a number between 0 and 9 (inclusive) to the character code of '0' gives you the character code of the corresponding digit.
do {
} while (number > 0);
is a normal do-while-loop which is only slightly different to a while-loop in the way that it checks the while-condition only after the body has been evaluated, not before as a while-loop would do.
char digit = (char) (number % 7 + '0');
is converting a digit from a number to a character. '0' needs to be added to the number because the number 0 is not the same as the character '0' (see ASCII tables for example) and therefore adding the character offset '0' to a digit (e. g. 7) will result in the number representing the character '7' and not the symbol at position 8 (0-based) in the character set.
What you're missing is, I think, the fact that char(7) doesn't give 7 as a character but rather the 7th character in the ASCII table.
Doing number modulo 7 will give you a number between 0 and 6, the rest of the division by 7. But if you want to convert it to a char, you need to find that number's index in the ASCII table. That index will be zero's index plus that number hence
char digit = (char) (number % 7 + '0');
Now, I'm not sure it's necessary to use char at all... You can concatenate a string with a number.

Why does this equation return the answer it does?

I am Confused as to why this returns 1;
(char)('0' + 11) = ; why?
Full code below where ending = 1;
char[] ending;
char a = (char)('0' + 11/10);
ending = new char[]{a, (char)('0' + 11)};
System.out.println(ending);
Char value of '0' is 48.
48 + 11 = 59
Char value of 59 is ';'.
You can check char values in integer value in any ASCII Character Set in internet.
In Java, char can be use as a int, short, byte, long with values between 0 and 65535 without any casting.
A better explanation is found in: Java char is also an int?
You are assigning '1' to variable a. '0' + 11/10 => '0' + 1
You are assigning a two letter string to endings. Le first letter is a ('1') the second is a semi colon. ('0' + 11).

How can an int be declared with ' ' and why is '2' == 50?

Question is: What gets displayed in console?
And I really have some problems with understanding.
Here is the code:
public static void felda(){
char[] felda = {'2',0x31,48};
for (int i = 0; i< felda.length; i++){
System.out.println(" : " + felda[i]);
}
System.out.println();
}
public static void feldb(){
int[] feldb = {'2',0x31,48};
for (int i = 0; i< feldb.length; i++){
System.out.println(" : " + feldb[i]);
}
System.out.println();
}
public static void feldc(){
int [] feldc = {'2',0x31,48};
for (int i = 0; i< feldc.length; i++){
System.out.println(" : " + (char) feldc[i]);
}
System.out.println();
}
So if I run in the Solution is:
: 2
: 1
: 0
: 50
: 49
: 48
: 2
: 1
: 0
So I don't understand how it is even possible to have an int definded with ' '.
And I find it very confusing how int feldb = '2' results in being 50 and int feldb=0x31 results in being 49.. dam this is all so confusing. I hope someone can enlighten me.
Edit: Why is char feldc = 48; resulting in being 0?
In Java, a char represents a Unicode character. But it's also in fact an unsigned integer, on 2 bytes, which can go from 0 to 216 - 1.
So,
char c = '2';
initializes c with the character '2'. And the numeric value of the character '2', in Unicode, is 50.
So, if you print it as a character, '2' will be printed. If you print it as a numeric value (as an int, using int c = '2'), 50 will be printed.
When doing
char feldc = 48;
you initialize feldc with the character whose numeric Unicode value is 48, and that character is the character '0'. It's thus equivalent to
char feldc = '0';
0x31 is a number written as an hexadecimal literal (that's what the 0xprefix means). When you write 31, the value is in decimal. It's equal to 1 * 100 + 3 * 101.
In hexadecimal, the base is 16 rather than 10. So 0x31 is equal to 1 * 160 + 3 * 161, which is equal to 49.
50 is the ASCII value of the '2' character. Defined like that its not the number 2.. its giving the ASCII value of a character. See this ASCII table and find the '2' char
http://ascii.cl/index.htm?content=mobile

The Character Class in Java

Here is a short program that counts the letters of any given word entered by the user.
I'm trying to figure out what the following lines actually do in this program:
counts[s.charAt(i) - 'a']++; // I don't understand what the - 'a' is doing
System.out.println((char)('a' + i) // I don't get what the 'a' + i actually does.
import java.util.Scanner;
public class Listing9_3 {
public static void main(String[] args) {
//Create a scanner
Scanner input = new Scanner (System.in);
System.out.println("Enter a word to find out the occurences of each letter: ");
String s = input.nextLine();
//Invoke the count Letters Method to count each letter
int[] counts = countLetters(s.toLowerCase());
//Display results
for(int i = 0; i< counts.length; i++){
if(counts[i] != 0)
System.out.println((char)('a' + i) + " appears " +
counts[i] + ((counts[i] == 1)? " time" : " times"));
***//I don't understand what the 'a' + i is doing
}
}
public static int[] countLetters(String s) {
int[] counts = new int [26]; // 26 letters in the alphabet
for(int i = 0; i < s.length(); i++){
if(Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
***// I don't understand what the - 'a' is doin
}
return counts;
}
}
Characters are a kind of integer in Java; the integer is a number associated with the character on the Unicode chart. Thus, 'a' is actually the integer 97; 'b' is 98, and so on in sequence up through 'z'. So s.charAt(i) returns a character; assuming that it is a lower-case letter in the English alphabet, subtracting 'a' from it gives the result 0 for 'a', 1 for 'b', 2 for 'c', and so on.
You can see the first 4096 characters of the Unicode chart at http://en.wikibooks.org/wiki/Unicode/Character_reference/0000-0FFF (and there will be references to other pages of the chart as well). You'll see 'a' there as U+0061 (which is hex, = 97 decimal).
Because you want your array to contains only the count of each letter from 'a' to 'z'.
So to index correctly each count of the letter within the array you would need a mapping letter -> index with 'a' -> 0, 'b' -> 1 to 'z' -> 25.
Each character is represented by a integer value on 16 bits (so from 0 to 65,535). You're only interested from the letters 'a' to 'z', which have respectively the values 97 and 122.
How would you get the mapping?
This can be done using the trick s.charAt(i) - 'a'.
This will ensure that the value returned by this operation is between 0 and 25 because you know that s.charAt(i) will return a character between 'a' and 'z' (you're converting the input of the user in lower case and using Character.isLetter)
Hence you got the desired mapping to count the occurences of each letter in the word.
On the other hand, (char)('a' + i) does the reverse operation. i varies from 0 to 25 and you respectively got the letters from 'a' to 'z'. You just need to cast the result of the addition to char otherwise you would see its unicode value be printed.
counts[s.charAt(i) - 'a']++; // I don't understand what the - 'a' is doing
assume charAT(i) is 'z'
now z-a will be equal to 25 (subtract the unicode / ASCII values).
so counts[25]=counts[25]+1; // just keeps track of count of each character

java ASCII conversion

Here is part of my code:
// randomly create lowercase ASCII values
int rLowercase1 = random.nextInt(122) + 97;
// convert ASCII to text
System.out.print((char)rLowercase1);
When I run my program, it displays symbols instead of lowercase letters. Is there any way that I can fix this so that it displays lowercase letters?
How about
rLowercase1 = 'a' + random.nextInt('z' - 'a' + 1);
Number of letters in alphabet can be calculated with 'z' - 'a' + 1 = 25 + 1 = 26.
Since random.nextInt(n) will return value from range [0; n) - n is excluded - it means that you can get 'a'+0 = 'a' as minimal value and 'a'+25 = 'z' as max value.
In other words your range of characters is from 'a' till 'z' (both included).
Change your code as:
int rLowercase1 = random.nextInt(26) + 97; // it will generate a-z
There are only 26 lower case letters:
int rLowercase1 = random.nextInt(26) + 97;
If you want only the 26 unaccented Latin letters, Change 122 to 26:
int rLowercase1 = random.nextInt(26) + 97;
I think the meaning of this is a little clearer if written like this:
int rLowercase1 = 'a' + random.nextInt(26);

Categories