java - 为什么会导致数组的长度打印在数组的末尾呢?

标签 java arrays javafx

我有一个 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/

相关文章:

java - JavaFX 中的 Parent 与 BorderPane

java - Web 服务器上的 Jar 文件错误

java - 如何在 java.time 的模式字符串中用时区格式化日期?

java.lang.UnsatisfiedLinkError dll.HelloJNI.sayHello()V

javafx - 在 JAVAFX 中处理时显示 gif 动画弹出窗口

java - 如何在 JavaFX 中为 ComboBox 中的项目添加值

java - stackoverflow错误递归平方根

javascript - 如果键存在,则使用键和值形成 JSON

arrays - 如何将数组从程序集传递到 C 函数

javascript - 使用 lodash/underscore .map() 函数的原因是什么?