使用do while循环向arrayList中添加元素



我不能在这段代码中添加2个值,我尝试了一个变量,但当我第二次试图从用户获取它没有工作。所以我把另一个,但我仍然不能从第一个变量添加值。如何解决这个问题?

import java.util.ArrayList;
import java.util.Scanner;
public class Suser {

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
char c;
String a ="";
String b ="";
ArrayList<String> tvList = new ArrayList<>();
do {
System.out.println("enter the tv show to add to the list");

a = sc.nextLine();
tvList.add(a);
b = sc.nextLine();
tvList.add(b);

System.out.println("do you need to add more values ? if yes press Y else N ");


c = sc.next().charAt(0);

} while(c=='Y' || c=='y');

System.out.println(tvList);
}
}

我将给出

下面的输出
enter the tv show to add to the list
dark
mindhunter
do you need to add more values ? if yes press Y else N 
y
enter the tv show to add to the list
mr robot
do you need to add more values ? if yes press Y else N 
y
enter the tv show to add to the list
after life
do you need to add more values ? if yes press Y else N 
n
[dark, mindhunter, , mr robot, , after life]

您的循环导致Scanner.nextLineScanner.next之后被调用,导致此问题

c=sc.next();执行后,光标将在同一行,因此下一个a=sc.nextLine();将解析空字符串,然后在b=sc.nextLine();执行时移动到下一行。这就是为什么第一个值没有被添加。

import java.util.ArrayList;
import java.util.Scanner;
public class Suser {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
char c;
String a ="";
String b ="";
ArrayList<String> tvList = new ArrayList<>();
do {
System.out.println("enter the tv show to add to the list");

a = sc.nextLine();
tvList.add(a);
b = sc.nextLine();
tvList.add(b);

System.out.println("do you need to add more values ? if yes press Y else N ");
c = sc.nextLine().charAt(0);

} while(c=='Y' || c=='y');

System.out.println(tvList);
}

}

最新更新