How to find most popular digit inside the number. for example I have number 222244, the most occurring digit is 2. Please help.
I have something like this, but don't really understand this first part of method, what is going on with int j = liczba.charAt(i) - 47; why 47 is here? anyone can explain it?
int digits[] = new int [10];
for(int i = 0; i <liczba.length(); i++){
int j = liczba.charAt(i) - 47;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for(int i=1;i <10; i++){
if(digits[i] >count){
count = digits[i];
digit = i;
}
}
return digit;
The line
int j = liczba.charAt(i) - 47;
Subtracts the character code of (i+1)th character liczba by 47. Refering to an ASCII table, 47 maps to "/", whose ASCII code is one less than "0".
Note that I am assuming the following, as your code appears to be in Java.
String indexes starts at zero i.e. first character has index 0, second character has index 1, and so on
It seems that characters and integers can be used interchangeably, because a character is internally represented by an integer, namely, the ASCII code of the character.
That said, the char type is actually an integer type, with less range
Hence, this code is to turn characters "0" to the integer 1, "1" to the integer 2, etc.
For example, when the 1st character (liczba.charAt(0)) is the character 0, liczba.charAt(0) returns character '0', which is also equals to number 48 -- because '0' has an ASCII code of 48.
Subtracts 48 with 47 gets 1, so it would convert character '0' to integer 1.
However it seems that this code could cause array index out of bounds error (assuming zero-based array indexes). when a digit is '9', this line returns 10. This would cause an aforementioned error. Unless this code's language's array are 1-based. However, even in this case, this line
int count = digits[0];
would simply fail. This code seems to fail with the common Off by one error
I believe this line should actually read
int j = liczba.charAt(i) - 48;
so that character '0' is converted to number 0.
If this still disturb you, you may change this line to
int j = liczba.charAt(i) - '0';
so it would be clearer. Subtract the code of '1' and the code of '0' gets you the integer 1, clear enough :)
Related
I encountered a code which some parts I do not understand. It has something to do with keeping count of letters in a string. I have commented the part that I do not get. I would appreciate any help. Thank you!
I tried looking it up online but none seem to answer my question.
public class test2 {
static int[] inventory;
public static final int ALPHABET = 26;
public static void main(String[] args) {
inventory = new int [ALPHABET];
String dog = "There goes the dog!";
int size = count(dog);
System.out.println(size);
}
private static int count(String data) {
data = data.toLowerCase();
int size = 0;
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isLetter(ch)) {
size++;
inventory[ch - 'a']++; // this I don't get
}
}
return size;
}
}
In this case, inventory is an array of size 26 which holds number of times each character appears in the string.
The statement you have put the comment on is trying to deduct the ASCII value of a which is 97 from the character in the string. For example, b's ASCII value is 98 and 'b' - 'a' is 1. So, inventory[1] is incremented i.e b appeared in your string once.
System.out.println(0 + 'c'); //ASCII value of 'c'; will print 99
System.out.println(0 + 'a'); //ASCII value of 'a'; will print 97
System.out.println('c' - 'a'); //Difference of ASCII values of characters; will print 99-97=2
In your case
inventory[ch - 'a']++;
ch will be some character.
ch - 'a' will be the distance of that character from 'a'. For example, as shown above, 'c' - 'a' = 2.
inventory[ch - 'a'] will point to the number at index ch - 'a' in the array.
inventory[ch - 'a']++ will increment that value by 1.
As per the above code, you're trying to count the number of each alphabets.
So, for each letter, let's assume you use a single bucket. Which is done by new int [ALPHABET];. So, you have 26 slots from 0 to 25.
Now, when you're counting the letters: Each letter has a value assigned to it (ASCII value). ASCII value of lower case a a is 97. But, in your slot, you want to add a to slot 0. So, what do you do: you subtract 97 i.e. you subtract value of a for each letter.
So now, a is stored in slot 0, b in slot 1 and so on.
so I am trying to set each of the letter in the alphabet to a number like a = 1
b = 2 c =3 and so on.
int char = "a";
int[] num = new int{26};
for (int i = 0; i <num.length; i++){
System.out.print(i);
But after this i got Stuck so if you possible help me out. So when the users input a word like cat it would out put 3-1-20.
You can subtract 'a' from each char and add 1. E.g.
String input = "cat";
for (char c : input.toCharArray()) {
System.out.print(c - 'a' + 1);
}
The code you posted doesn't compile as you can't assign a String to an int and char is a reserved word (name of a primitive type)
int char = "a";
You also mention that you want the output formatted like this "3-1-20". This is one way to achieve that :
String input = "cat";
String[] out = new String[input.length()];
for (int i = 0; i < input.length(); ++i) {
out[i] = Integer.toString(input.charAt(i) - 'a' + 1);
}
System.out.println(String.join("-", out));
Both versions work only for lowercase English letters (a to z)
Assigning a number to a character is called an "encoding". As computers can only handle numbers internally, this happens all the time. Even this text here is encoded (probably into an encoding called "UTF-8") and then the resulting number is stored somewhere.
One very basic encoding is the so called ASCII (American Standard Code for Information Interchange). ASCII already does what you want, it assigns a number to each character, only that the number for "A" is 65 instead 1.
So, how does that help? We can assume that for the character A-z, the numeric value of a char is equal to the ASCII code (it's not true for every character, but for the most basic ones, it's good enough).
And this is why everyone here tells you to subtract 'A' or 'a': Your character is a char, which is a character, but also the numeric value of that character, so you can subtract 'A' (again, a char) and add 1:
'B' - 'A' + 1 = 2
because...
66 (numeric value of 'B') - 65 (numeric value of 'A') + 1 = 2
Actually, char is not ASCII, but UTF-8, but there it starts to get slightly bit more complex, so ASCII will suffice for the moment.
the best way of doing this is to convert the String to a byte[], like this:
char[] buffer = str.toCharArray();
Then each of the characters can be converted to their byte-value (which are constants for a certain encoding), like this:
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
}
Now look at the resulting values and subtract/add some value to get the desired results!
Here is what the teacher asked me to do:
Enter a phone number (set up a string-type object for the phone number)
example:
(703) 323-3000
Display the phone number, using a format like the following:
Example 1:
The phone number you entered is 703-323-3000.
Display the content of the array that holds the count for each digit in the string. Use a format similar to the following:
Example:
Digit 0 showed up 4 times.
Digit 1 showed up 0 times.
Digit 2 showed up 1 times.
Digit 3 showed up 4 times.
Digit 4 showed up 0 times.
Digit 5 showed up 0 times.
Digit 6 showed up 0 times.
Digit 7 showed up 1 times.
Digit 8 showed up 0 times.
Digit 9 showed up 0 times
The teacher also provided us with an algorithm as a hint:
set up an integer array of size 10
initialize each element to zero
input string of phone number
set SIZE = length of the string
set up a loop to iterate SIZE times
{
get next character
update array appropriately
(for example: if the character is '7' then increment array[7] by 1.
}
Display BOTH using appropriate messages:
the original phone number
contents of the array (using a loop).
Here is My code but it shows the error I mentioned when i use the equals() method, and displays a wrong answer if i use ==. Please Help.
public class Phones
{
public static void main(String[] args)
{
int Num[] = {0,0,0,0,0,0,0,0,0,0};
String Phone = "703-323-3000";
int SIZE = Phone.length() - 1;
for(int count=0; count<= SIZE; count++)
{
for(int counter = 0; counter <= SIZE; counter++)
{
if(Phone.charAt(counter).equals(count))
Num[count]++;
}
System.out.println("Digit " + count + " showed up " + Num[count] + " times");
}
}
}
This is my first time on this site, so sorry in advance if this is too long or incomprehensible. Thank you.
The reason you get the wrong answer with == is that you're comparing a char with an int incorrectly. In short, you're comparing counter with the unicode value of the characters, rather than with the number that the character represents. (For "normal" characters like letters, numbers and simple punctuation, the unicode values are the same as the ASCII values.)
The char '0' does not have an int value 0 -- it has the unicode value for the char 0, which is 0x0030 (aka 48 in base 10 -- the 0x format shows it in hex). By comparing the char the way you're doing, the first comparison will only be true if the char is the so-called "null char" 0x0000 (not to be confused with null, which is a null reference!), which won't happen for any sort of "normal" input.
Instead, you need a way to compare chars with ints. The easiest way to do this is to subtract the '0' char's value from the current char:
int charDistanceFromZero = Phone.charAt(counter) - '0';
If that distance is less than 0 or greater than 9, you have a char that's not a number. Otherwise, charDistanceFromZero is the offset you need into the array.
This works because the characters for the number digits start at 0 and are sequential from there. Try computing charDistanceFromZero for a few of them to get a feel for how it works out for getting the array index.
charAt will return a value of type char, which is the reason why you cannot do .equals(...).
Also, the characters representing the digits are in ['0' .. '9'], which isn't the same as the interval [0 .. 9]. You need to translate the range by subtracting '0'.
The reason for your error is that charAt returns a char, which is a primitive type. You need to have an object, not a primitive, in order to be able to call a method, such as .equals. Moreover, when you tried to use == in place of .equals, you were comparing a char to an int value. It's all right to do this, so long as you remember that the int value of a character is its encoded value, so 48 for '0', 49 for '1' and so on.
To solve this problem, it's best to use the methods that come for free in Java's Character class; notably isDigit, which determines whether a character is a digit, and getNumericValue, which converts a character to the number that it represents.
It's also possible to dispense with the outer loop entirely, since once you've converted each digit character to its numeric value, you already have the index in the array that you want to increment. So here is a much cleaner solution, that does not use nested loops at all.
public class Phones{
public static void main(String[] args){
int counters[] = new int[10];
String phone = "703-323-3000";
for (char eachCharacter : phone.toCharArray()) {
if (Character.isDigit(eachCharacter)) {
int digit = Character.getNumericValue(eachCharacter);
counters[digit]++;
}
}
for(int digit = 0; digit < 10; digit++) {
if (counters[digit] != 0) {
System.out.format("Digit %d showed up %d times.%n", digit, counters[digit]);
}
}
}
}
Here, the first loop traverses your input string, incrementing the array index corresponding to each digit in the string. The second loop just prints out the counts that it's found.
Other answers are fine... But to reduce ambiguity in code I generally just send the string into a char array before doing any control flows... And as noted, 'Zero' is at Unicode Code Point 48 so you need to subtract that value from the character index.
char[] number = "212-555-1212".toCharArray();
for(int i = 0; i < numbers.length; i++) {
// do something groovy with numbers[i] - 48
}
So for this solution you might do something like this....
String phone = "212-555-1212".replaceAll( "[^\\d]", "" );
int[] nums = new int[phone.length()];
int[] queue = new int[phone.length()];
for(int i = 0; i < nums.length; i++) {
nums[i] = phone.toCharArray()[i] - 48;
for(int num : nums) {
if( nums[i] == num ) {
queue[i] += 1;
}
}
System.out.println( "Number: " + nums[i] + " Appeared: " + queue[i] + " times." );
}
I'm trying to find the high and low number in an array, but I'm not sure why my codes not working correctly. It's giving me the output of 0 and 56. I understand why it's giving the 0, but where did the 56 come from?
package test;
public class Test {
public static void main(String[] args) {
int[] numbs = { '2', '4', '2', '8', '4', '2', '5'};
int count = 0;
int low = 0;
int high = 0;
while(count < numbs.length)
{
if(numbs[count]< low) {
low = numbs[count];
}
if(numbs[count]> high) {
high = numbs[count];
}
count++;
}
System.out.println(low);
System.out.println(high);
}
}
You need to start the low low enough; currently, you start it at zero - too low to "catch" the lowest element of the array.
There are two ways to deal with this:
Use Integer.MAX_VALUE and Integer.MIN_VALUE to start the high and low, or
Use the initial element of the array to start both high and low, then process the array starting with the second element.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
P.S. You would find strange numbers printed, because you used characters instead of integers:
int[] numbs = { 2, 4, 2, 8, 4, 2, 5};
Also.. It is probably printing the ASCII representation... use actual integers (I'm not sure if your usage of chars was intentional).
You use chars instead of ints at the array init block, this is immediately converted to ints to fit in the int[] array, but don't use its actual value, but the unicode value, where: 2 = 52 and 8 = 56.
'8' is char literal, not an int. The Java Language Specification defines char as follows:
The integral types are byte, short, int, and long [...] and char, whose values are 16-bit unsigned integers representing UTF-16 code units.
If you use a char where an int is expected, the char is implicitly converted to int. Since char is a numeric type, this will preserve its numeric value, i.e. its UTF-16 code point. The utf-16 code point of 8 is 56.
Treating char as a numeric type can be useful. For instance, we can compute the n-th letter of the alphabet by
char nthLetter = (char) `A` + n;
or find the numeric value of a digit by
if ('0' <= digit && digit <= '9')
return value = digit - '0';
else
throw new IllegalArgumentException(digit);
You should set both the low and high to the value in the first position of the array.
int low = numbs[0];
int high = numbs[0];
If the first position is indeed the lowest value it will never be swapped, otherwise it will be swapped with a lower number, the same happen to the highest number.
You want an array of ints that you should declared like such:
int[] numbs = {2, 4, 2, 8, 4, 2, 5};
You are getting 56 as the highest value because the decimal representation of the char '8' according to the ASCII table is 56.
I'm trying to convert a string filled with 16 digits into an array of ints where each index holds the digit of its respective index in the string. I'm writing a program where I need to do math on individual ints in the string, but all of the methods I've tried don't seem to work. I can't split by a character, either, because the user is inputting the number.
Here's what I have tried.
//Directly converting from char to int
//(returns different values like 49 instead of 1?)
//I also tried converting to an array of char, which worked,
//but then when I converted
//the array of char to an array of ints, it still gave me weird numbers.
for (int count = 0; count <=15; count++)
{
intArray[count] = UserInput.charAt(count);
}
//Converting the string to an int and then using division to grab each digit,
//but it throws the following error (perhaps it's too long?):
// "java.lang.NumberFormatException: For input string: "1234567890123456""
int varX = Integer.parseInt(UserInput);
int varY = 1;
for (count=0; count<=15; count++)
{
intArray[count]= (varX / varY * 10);
}
Any idea what I should do?
how about this:
for (int count = 0; count < userInput.length; ++count)
intArray[count] = userInput.charAt(count)-'0';
I think that the thing that is a bit confusing here is that ints and chars can be interpited as eachother. The int value for the character '1' is actually 49.
Here is a solution:
for (int i = 0; i < 16; i++) {
intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}
The substring method returns a part of the string as another string, not a character, and this can be parsed to an int.
Some tips:
I changed <= 15 to < 16. This is the convetion and will tell you how many loop interations you will actually go throug (16)
I changed "count" to "i". Another convention...