gpt4 book ai didi

java - 如何将字符串转换为 char 以填充 Java 中的数组?

转载 作者:行者123 更新时间:2023-11-30 07:03:20 24 4
gpt4 key购买 nike

如标题所述,我希望创建一个字符数组,用户输入应存储为字符。我这样做是为了创建有缺陷的代码,这些代码可能会成为缓冲区溢出的牺牲品。在我完成这项工作后,我将截断输入并且不会导致缓冲区溢出。但是当我被指示这样做时,我无法弄清楚如何在 Java 中将我的字符串存储为 char。这是我到目前为止的代码:

import java.util.Scanner;





public class buggyCode {

public buggyCode() {
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kb = new Scanner(System.in);
String input1, input2, input3, input4, input5, input6, input7, input8, input9, input10;
char[] thisArray = new char [150];

thisArray[0]=toChar(input1);
thisArray[1]=input2;
thisArray[3]=input3;


System.out.println("Enter some characters. We are going to do this for a while");
input1 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input2 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input3 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input4 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input5 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input6 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input7 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input8 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input9 = kb.nextLine();
System.out.println("Enter some characters. We are going to do this for a while");
input10 = kb.nextLine();

}

}

最佳答案

首先,这行代码将在启动程序时自动失败,删除:

thisArray[0]=toChar(input1);
thisArray[1]=input2;
thisArray[3]=input3;

要获得干净的代码,您可以放弃使用字符串并使用 for loop 循环它们

for(int i = 0; i < 10; i++)
{
System.out.println("Enter some characters. We are going to do this for a while");
thisArray[i] = kb.nextLine().toCharArray()[0]; //store the first index of string to the thisArray array
}

上面你可以看到 nextLine() 然后被转换为 char 数组并获得第一个索引,然后存储在你的 char 数组中

关于java - 如何将字符串转换为 char 以填充 Java 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com