[英]How can I get the value of a variable from a class?
So I'm new to java and decided to mess around a little, I wrote a class that converts a string to an array made out of the ascii values of the characters in the string, but I don't know how to get the value of the variable i.所以我是 Java 新手并决定稍微搞砸,我写了一个类,将字符串转换为由字符串中字符的 ascii 值组成的数组,但我不知道如何获取该值变量 i。 I know it's easier to use a list but I'm really curious how to make this work.我知道使用列表更容易,但我真的很好奇如何进行这项工作。 This is the code:这是代码:
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()
will convert the String
to codepoints (ie numbers of the characters). txt.codePoints().toArray()
将String
转换为代码点(即字符数)。
For example:例如:
import java.util.Arrays;
public class Main {
public static void main(final String[] args) {
System.out.println(Arrays.toString("abc".codePoints().toArray()));
}
}
will print:将打印:
[97, 98, 99]
where 97 corresponds to 'a', 98 to 'b' and 99 to 'c'.其中 97 对应于“a”,98 对应于“b”,99 对应于“c”。
The problem with your code is ch -1
which should be just ch
.您的代码的问题是ch -1
应该只是ch
。
You should do it as follows:你应该这样做:
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;
}
}
Output:输出:
[97, 66, 99]
Alternatively , you can do it as follows:或者,您可以按如下方式进行:
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;
}
}
Output:输出:
[97, 66, 99]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.