正如标题所述,我希望创建一个char数组,用户输入应该存储为char。我这样做是为了创建错误的代码,它可能成为缓冲区溢出的牺牲品。我有这个工作后,我将截断输入,而不是导致缓冲区溢出。但是当我被指示这样做时,我无法弄清楚如何将我的字符串存储为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();
}
}
答案 0 :(得分:3)
首先,这行代码会在启动程序时自动失败,删除它:
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数组并获得第一个索引然后存储在ur char数组
答案 1 :(得分:1)
每次你写inputN
两次以上,N
被数字替换,你就知道你需要一个数组。大多数情况下,当您发现自己通过最少的更改复制粘贴代码时,您就知道需要循环。
我要在每10个索引处填充数组,从150开始下降。
以下是如何正确地做到这一点:
char[] input = new char[150];
for (int i = 0 ; i != 10 ; i++) {
System.out.println("Enter some characters. We are going to do this for a while.");
char[] buf = kb.nextLine().toCharArray();
// Copy the data into input
System.arraycopy(buf, 0, input, 140-(i*10), Math.min(buf.length, 10));
}