我的 method.add(int) 不会将用户输入添加到我的数组中



我正在尝试创建一个数组,该数组询问用户的长度,然后要求用户一次在数组中输入多个单词。但是我的代码句子.add(s(;不会将我的"S"变量添加到我的数组列表中,称为句子。你能不能看看我的代码,看看我做错了什么。编辑运行时,在输入数组的长度后,程序要求我输入一个单词,但立即 用两个括号 [] 打印在其下方的行上,并在那里停止程序。如果有人知道为什么这很开心,我将不胜感激!

import java.util.Scanner;
import java.util.ArrayList;
public class UsingWords
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an array length ");
int lengthArray = scan.nextInt();
ArrayList<String[]> sentences = new ArrayList<String[]>();
for (int i=0; i <= lengthArray; i++); { 
System.out.println("Please enter a word: "); 
String s = scan.nextLine();
sentences.add(s);
}
System.out.println(Arrays.toString(sentences));
}
}

它不起作用,因为您声明了一个 ArrayList of String[] 并尝试在其中添加一个字符串。

sentences应该是ArrayList<String>类型。

我不知道你为什么要将数组与ArrayList结合使用。 我怀疑你想要这样的东西:

//remove the "[]" here
ArrayList<String> sentences = new ArrayList<String>();
for (int i=0; i <= lengthArray; i++); { 
System.out.println("Please enter a word: "); 
String s = scan.nextLine();
sentences.add(s);
}
//..and the Arrays.toString here
System.out.println(sentences);

最新更新