import java.util.Scanner;
public class StringArray {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("How many names do you wish to enter?");
int numOfNames = read.nextInt();
String [] names = new String[numOfNames];
我收到一条错误,说String无法转换为int。 我尝试过在网上找到的东西,比如尝试将int转换为字符串等,但是没有用。 我的源代码在这里:
import java.util.Scanner;
public class ArrayDemoS {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("How many names do you wish to enter?");
int numOfNames = read.nextInt();
String [] names = new String[6];
System.out.println("Enter the names.");
int items = 0;
do {
names[items] = read.nextLine();
} while ( ++items <= numOfNames);
System.out.println("You entered the following names");
for ( int i = 0; i <= numOfNames; i++) {
System.out.print(names[i] + " ");
}
System.out.println();
}
}
我将大小设置为6,假设用户将输入5个名称。 使用ArrayList等可能有其他方法可以做到这一点,但我还没有了解它们。当数组由int类型数据组成时,我能够完成相同的任务。我希望能够为String类型做到这一点。在此先感谢:)
答案 0 :(得分:0)
这很好。
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("How many names do you wish to enter?");
int numOfNames = read.nextInt();
String [] names = new String[numOfNames];
System.out.println("Enter the names.");
int items = 0;
names[items] = read.nextLine();
while ( items < numOfNames)
{
names[items] = read.nextLine();
items++;
}
System.out.println("You entered the following names");
for ( int i = 0; i < numOfNames; i++) {
System.out.print(names[i] + " ");
}
System.out.println();
}