[英]How can I change the value of a static class variable from a method, then get it from an other method?
[英]How can I get the value of a variable from a class?
所以我是 Java 新手並決定稍微搞砸,我寫了一個類,將字符串轉換為由字符串中字符的 ascii 值組成的數組,但我不知道如何獲取該值變量 i。 我知道使用列表更容易,但我真的很好奇如何進行這項工作。 這是代碼:
public class ToAscii {
static int[] toAscii(String txt){
int[] array = new int[1000];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch -1;
i++;
}
return array;
}
}
txt.codePoints().toArray()
將String
轉換為代碼點(即字符數)。
例如:
import java.util.Arrays;
public class Main {
public static void main(final String[] args) {
System.out.println(Arrays.toString("abc".codePoints().toArray()));
}
}
將打印:
[97, 98, 99]
其中 97 對應於“a”,98 對應於“b”,99 對應於“c”。
您的代碼的問題是ch -1
應該只是ch
。
你應該這樣做:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt){
int[] array = new int[txt.length()];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch;
i++;
}
return array;
}
}
輸出:
[97, 66, 99]
或者,您可以按如下方式進行:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt) {
int[] array = new int[txt.length()];
char[] ascii1 = txt.toCharArray();
for (int i = 0; i < array.length; i++) {
array[i] = ascii1[i];
}
return array;
}
}
輸出:
[97, 66, 99]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.