Home > Blockchain >  adding elements to arrayList with do while loop
adding elements to arrayList with do while loop

Time:04-25

i can't add 2 values in this code , i tried with one variable but when i tried to fetch from user for the second time it didnt worked .so i put another one but still i can't add value from first variable . how can i resolve this ?

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

}

I will give the output below

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]

CodePudding user response:

Your loop is causing Scanner.nextLine to be called after Scanner.next, causing this issue.

CodePudding user response:

after the line c=sc.next(); is executed the cursor will be at the same line so the next a=sc.nextLine(); will parse an empty string and then move to the next line when b=sc.nextLine(); is executed.That is why the first value is no added.

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

}

  • Related