0

I am a newbie in Java, and currently dealing with a code that implements array.

Scanner sc= new Scanner(System.in);
String str=sc.nextLine();
int count[]= new int[25];
int len = str.length(); 

// Initialize count array index 
for (int i = 0; i < len; i++) 
    {count[str.charAt(i)]++; } //This line is the issue.

I want to know if charAt() returns char value then how count[] (integer array)can store that, and if it does then how. I have extracted the source code from this linkenter link description here

Thank You.

4 Answers4

0

The answers at this question go into depth about which char to int conversions are permitted and why.

To give a simple answer for your case, the char is being converted to an int based on it's ASCII Value.

For example, if the character is 'A' it is converted to 65, 'B' to 66 and so on. Each character will have an associated integer code, which you can check online on sites like ASCII Table

shriakhilc
  • 2,922
  • 2
  • 12
  • 17
  • That said, it is weird that your code isn't crashing at run time. Your `char[]` size is defined as 25, which means the indices will range from 0-24. As I have mentioned in examples, normal user input characters are way above this range, and you should be getting `IndexOutOfBounds`. – shriakhilc Oct 12 '18 at 08:42
0

If you need to store the numerical representation of every chart you have in your string you can do something like that:

int[] nums = new int[length];

for(int i = 0; i < length; i++){
   char character = testStr.charAt(i);
   nums[i] = Character.getNumericValue(character);
}

Happy coding !!!

0

Maps are not arrays. An array have numerical indexes starting at 0, and you try to use character values as indexes...

So you have 2 possible paths there:

  • use a Map<char, int> that will be natively indexed by characters - but you will have to take care of setting a 1 value the first time you encounter a character. Pros: accept non alphabet characters, cons: more complex processing
  • stick to an array and use a conversion from a char to a number in the [0-26[ range. Character.getNumericValue is a good star point because it maps all alphabets in the range [10-36[ - by the way you need an array of size 26 not 25

You code could become:

Scanner sc= new Scanner(System.in);
String str=sc.nextLine();
int count[]= new int[26];
int len = str.length(); 

// Initialize count array index 
for (int i = 0; i < len; i++) {
    val = Character.getNumericValue(str.charAt(i)) - 10;
    if (val >= 0) {  // ok we have an alpha character
        count[val]++;
    } 
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

This method for counting characters will not work properly if input is out of ASCII range. Here is an elegant way of doing the same job on the full Unicode range (including codepoint greater than 216) using maps and streams:

import java.util.Map;
import java.util.stream.Collectors;

public class Counter {

    public static void main(String [] args) {
        String input = "geeksforgeeks \uD83D\uDE02";
        Map<String, Integer> countMap = input.codePoints()
                .mapToObj(codePoint -> new String(Character.toChars(codePoint)))
                .collect(Collectors.toMap(c -> c, c -> 1, (n1, n2) -> n1 + n2));
        System.out.println(countMap);
    }
}

The output is

geeksforgeeks

{ =1, r=1, s=2, e=4, f=1, g=2, k=2, =1, o=1}

Note that this special "drawing" , is made of 2 chars. It's codePoint (hexadecimal) is D8 3D DE 02, and is named "FACE WITH TEARS OF JOY".

If now run the same program by replacing input.codePoints() with input.chars(), you get the following wrong result:

geeksforgeeks

{ =1, ?=1, r=1, s=2, e=4, f=1, g=2, k=2, ?=1, o=1}


Special thanks to Xah Lee

Community
  • 1
  • 1
Benoit
  • 5,118
  • 2
  • 24
  • 43