我有一个 JavaFX 文本字段,我从中获取字符串输入。我使用 toCharArray() 将字符串作为字符数组传递。但由于某种无法解释的原因,数组的长度出现在数组之后。有什么想法可能导致这种情况吗?我预计输入为 16 个元素,因此我对其进行硬编码,但由于某种原因,我得到的结果是 18 个元素,最后两个元素为 1、6。(当我更改输入长度时,最后两个元素如下)。现在我知道在 Java 中称其为错误是愚蠢的,因此问题就在我这边,但对于我的生活,我无法弄清楚?
public class something extends Application {
String input;
char[] chars;
public void start(Stage primaryStage) {
TextField field = new TextField("Enter");
input = field.getText();
Button btn = new Button("Check");
btn.setOnAction(e -> validator(input));
}
public void validator(String input) {
chars = new char[input.length()];
System.out.println(input.length()); // this still shows 16
if (chars.length == 16) {
chars = input.toCharArray();
}
for (int i = 0; i < chars.length; i++){
System.out.print(chars[i]);
} //here the problem occurs, when I try to print the array
System.out.println(chars.length); //this also shows 16
if (chars[0] == '4'){
System.out.println("yayy");
check(input);
}
else {
// shows an alert
}
}
}
public void check(String str){
// some other code that works properly
}
public static void main(String[] args) {
Application.launch(args);
}
最佳答案
请注意,每个字符都用 print
打印,而不是 println
。
for (int i = 0; i < chars.length; i++){
System.out.print(chars[i]);
}
System.out.println(); // To a new line
System.out.println(chars.length); //this also shows 16
关于java - 为什么会导致数组的长度打印在数组的末尾呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51402544/