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

我有一个 JavaFX textField,从中我可以得到一个字符串输入。我正在使用 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);

}



潇湘沐
浏览 216回答 2
2回答

慕哥6287543

请注意,每个字符都打印有print,而不是println。for (int i = 0; i < chars.length; i++){&nbsp; &nbsp; System.out.print(chars[i]);}System.out.println(); // To a new lineSystem.out.println(chars.length); //this also shows 16

肥皂起泡泡

首先,Java 不会将数组的长度附加到数组中。也没有String.toCharArray。所以,无论你看到什么,这都不是解释。另一方面,我无法解释到底发生了什么,因为您没有向我们提供实际的输入和输出。即便如此,从您的代码中可以明显看出一些明显的误解首先,这个语句没有做任何有用的事情:chars = new char[input.length()];为什么?因为chars = input.toCharArray();将返回一个全新的数组。它不会填充您之前分配的字符数组。(任务只是取代了它......)第二个误解是这样的:if (chars[0] == 4){&nbsp; &nbsp; &nbsp;....}目前尚不清楚您期望测试做什么,但它不是在测试字符“4”。它正在测试 Unicode 代码点 \u0004 ... 这是 ASCIIEOT控制字符,或CNTRL-D在典型的西方键盘上。简而言之,验证可能没有测试您所期望的。(为什么您希望用户输入控制字符?)要测试字符 '4' ... 使用字符文字。单引号。if (chars[0] == '4'){&nbsp; &nbsp; &nbsp;....}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java