使用 do while 循环将元素添加到 arrayList

adding elements to arrayList with do while loop

我无法在此代码中添加 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 之后被调用,导致 this 问题。

c=sc.next();执行后,光标将在同一行,因此下一个a=sc.nextLine();将解析一个空字符串,然后在b=sc.nextLine();时移动到下一行executed.That 是第一个值未添加的原因。

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);
}

}