正如标题所述,我希望创建一个字符数组,并且用户输入应存储为字符。我这样做是为了创建有缺陷的代码,这些代码可能会成为缓冲区溢出的牺牲品。完成此工作后,我将截断输入并且不会导致缓冲区溢出。但是当我被指示这样做时,我很难弄清楚如何在 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;
要获得干净的代码,您可以放弃使用 string 并使用 for 循环
循环它们
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 - 如何在Java中将字符串转换为字符来填充数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468311/