[英]ASCII: Cannot invoke length() on the primitive type int
作為創建哈希表的一部分,我需要將字符串的符號轉換為 ASCII,並且需要該 ASCII 的長度。 我在這個站點上發現在字符串前面轉換 int 以將其轉換為 ASCII 就足夠了,但我不能將它用作對象。
public int hash(String x) {
int stringLength = x.length();
for (int i = 0; i < stringLength; i++) {
char character = x.charAt(i);
int ascii = (int) character;
int z = ascii.length();
}
我希望獲得一些整數方法,但它似乎不起作用,並且我收到錯誤Cannot invoke length() on the primitive type int
在ascii.length()
處Cannot invoke length() on the primitive type int
ascii.length()
;
我假設您正在嘗試獲取字符的值,因為這實際上是 ascii 代碼:
為此,請使用 Character 類而不是 char 原語:
public int hash(String x) {
int stringLength = x.length();
for (int i = 0; i < stringLength; i++) {
Character character = x.charAt(i);
int ascii = character.charValue();
}
原語不是對象,不能解除引用。
你可以做的是使用一個整數,它是一個包裝一個 int 的類,使用它的 toString() 方法並在結果上使用 length()。
就像是
char character = x.charAt(i);
int z = Integer.valueOf((int) character).toString().length();
(編輯因為 valueOf 不帶字符)
這將告訴您字符的代碼十進制表示有多少位數。 我不明白你為什么需要它,但這就是我理解你的問題的方式。
要獲取 ASCII 代碼的長度,您可以將值轉換為字符串並獲取其長度:
public int hash(String x) {
int stringLength = x.length();
String value;
int ascii, asciiLength;
for (int i = 0; i < stringLength; i++) {
ascii = x.charAt(i); // chars are just fancy numbers. This does an implicit cast to int
value = Integer.toString(ascii);
asciiLength = value.length();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.