![](/img/trans.png)
[英]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.