此代码无法编译,因为子字符串方法只能在字符串上调用,如果我没记错的话,不能在字符串数组上调用。在上面的代码中,timestamp 被声明为一个有 40 个索引的 String 数组。
同样在此代码中,您要求用户输入并将其分配给该行中的名称:
name = sc.nextLine();
然后您尝试将用户刚刚键入的内容替换为下一行时间戳中存储的内容,这什么都没有,并且会删除名称中存储的内容:
name = timestamp.substring(0,20);
再一次,这无论如何也行不通,因为时间戳是一个由 40 个字符串组成的数组,而不是一个特定的字符串。为了调用子字符串,它必须是一个特定的字符串。
我知道这可能对您尝试做的事情没有多大帮助,但希望它可以帮助您理解为什么这不起作用。
如果您可以通过具体示例回复您正在尝试做的事情,我可以帮助您进一步指导。例如,假设您希望用户输入他们的姓名“John Smith”,然后您希望将其分成两个不同字符串变量或字符串数组中的名字和姓氏。越具体你想做的事就越好。祝你好运:)
开始编辑
好的,如果我理解您的操作正确,您可能想尝试以下几件事。
//Since each index will only be holding one character,
//it makes sense to use char array instead of a string array.
//This next line creates a char array with 40 empty indexes.
char[] timestamp = new char[40];
//The variable name to store user input as a string.
String name;
//message to user to input name
System.out.println("Pls enter a name and surname");
//Create a scanner to get input from keyboard, and store user input in the name variable
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
//if you wanted the length of the char array to be the same
//as the characters in name, it would make more sense to declare it here like this
//instead of declaring it above.
char[] timestamp = new char[name.length()];
//For loop, loops through each character in the string and stores in
//indexes of timestamp char array.
for(int i=0; i<name.length;i++)
{
timestamp[i] = name.charAt(i);
}
如果您只想分隔名字和姓氏,您可以做的另一件事是像这样拆分它。
String[] seperateName = name.split(" ");
该行将在找到空格时拆分字符串并将其放入seperateName数组的索引中。所以如果名字是“John Smith”,sperateName[0] = John 和 seperateName[1] = Smith。