public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String user_input = scnr.nextLine();
System.out.println(user_input.charAt(0));
int listSize = (int) (user_input.charAt(0));
String[] wordsList = new String[listSize];
user_input = user_input.substring(2);
wordsList = user_input.split(" ");
for (int i =0; i<listSize; i ){
int frequency = getWordFrequency(wordsList, listSize, wordsList[i]);
System.out.println(wordsList[i] " " frequency );
}
}
This is the code if I give "5 hey Hi Mark hi mark" the list size is the ASCII value of 5 instead of int 5.
Tried changing the char directly into the int value. It is giving me an ASCII value.
CodePudding user response:
There are more characters representing digits than just 0 to 9. For example, there's ۲, which is the arabic-indic variant of 2.
Hence, use the right unicode aware methods for the job:
int value = Character.digit('\u06F2', 10);
System.out.println(value);
This will print '2'. 06F2 is the unicode point for ۲, you can just put ۲ straight in the source file, but if your compiler and editor don't agree on charset encoding it would fail, the backslash u escape is 'safer'.
If you're limited to '0'-'9', they take up consecutive spots in the unicode table, so you can subtract '0'
:
char v = '5';
int c = v - '0';
System.out.println(c); // prints 5
But, don't. Use Character.digit
. The , 10
in the digit method is the 'radix', you probably want 10. Feel free to peruse the javadoc of Character::digit.
If you have string containing a number (consisting of potentially more than one digit symbol), theres Integer.parseInt
, which is also capable of parsing most number symbols:
String value = "\u06F2\u06F2";
System.out.println(Integer.parseInt(value));
prints 22.
CodePudding user response:
Subtract '0'
or use Character.getNumericValue
.
int listSize = user_input.charAt(0) - '0';
For integers with more than one digit, use Integer.parseInt
.