我希望用户输入一个字符串,然后将该字符串的每个字符分配给数组中的元素。
到目前为止,这是我的代码:
import java.util.Scanner;
public class Apples {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
int arrayLength = name.length();
String ArrayName[] = new String [arrayLength];
for(int counter = 0; counter < arrayLength; counter++){
ArrayName[counter] = name.substring(counter);
System.out.println("Element No" + counter + ": " + name.substring(counter));
}
}
答案 0 :(得分:0)
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
int arrayLength = name.length();
String ArrayName[] = new String [arrayLength];
char[] chars = name.toCharArray();
for(int counter = 0; counter < arrayLength; counter++) {
ArrayName[counter] = chars[counter] + "";
System.out.println("Element No" + counter + ": " + name.substring(counter));
}
}
答案 1 :(得分:0)
import java.util.Scanner;
public class Apples {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
int arrayLength = name.length();
int temp = 1;
String ArrayName[] = new String [arrayLength];
for(int counter = 0; counter < arrayLength; counter++){
ArrayName[counter] = name.substring(counter, name.length()-name.length()+temp);// HAD TO ADD THIS TO GET IT WORKING
temp++;
System.out.println("Element No" + counter + ": " + ArrayName[counter]);
}
答案 2 :(得分:0)
您需要使用String的toCharArray()
方法。如果在String上调用此方法,它将完全按照您的需要返回chars
数组:
import java.util.Scanner;
public class Apples {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
char[] nameArray = name.toCharArray();
for(int counter = 0; counter < nameArray.length; counter++){
System.out.println("Element No" + counter + ": " + nameArray[counter]);
}
}
}
查看上面链接的文档,查看其工作原理的完整说明以及可以在String对象上调用的其他方法。