[英]how do i use do-while loop to prompt for and read the strings from the user? Array Lists
I keep getting an error with my code specifically at我的代码一直出现错误,特别是在
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
the error tells me "; expected" what am I doing wrong here?错误告诉我“;预期”我在这里做错了什么?
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = 0;
numLines = scnr.nextInt();
System.out.println();
ArrayList lines = new ArrayList();
scnr.nextLine();
int i = 0;
do{
System.out.println("Enter your text: ");
String text = scnr.nextLine();
ArrayList<String> input = new ArrayList<String>();
i++;
for (i = 0; i < numLines; i++)
{
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
}
for (String element: ArrayList<String> Lines)
{
System.out.println(element);
}
} while(i != 0);
As you have正如你所拥有的
ArrayList<String> input = new ArrayList<String>();
within your loop, it means that it will get re-declared and initialised for every iteration of that loop, so move this declaration to before your do
在您的循环中,这意味着它将为该循环的每次迭代重新声明和初始化,因此请将此声明移至您的
do
之前
Next, to add to this loop, use add
method接下来,要添加到此循环中,请使用
add
方法
String text = scnr.nextLine();
input.add (text);
To simplify, you do not need a do
as you have a number of times that you want to loop为简化起见,您不需要
do
,因为您要循环多次
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = scnr.nextInt();
System.out.println();
scnr.nextLine();
ArrayList <String> lines = new ArrayList <> ();
for (int i = 0; i < numLines; i++) {
System.out.println("Enter word...");
String text = scnr.nextLine();
lines.add(text);
}
To print your list, you can then do要打印您的列表,您可以执行以下操作
for (int x = 0; x < lines.size(); x++) {
System.out.println (lines.get(x));
}
output输出
how many lines of text do you want to enter
5
Enter word...
one
Enter word...
two
Enter word...
three
Enter word...
four
Enter word...
five
one
two
three
four
five
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.