1

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]
0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

how can i resolve this ? when i tried String type for the answer then it didnt loop !
Use c = sc.nextLine().charAt(0) instead of c = sc.next().charAt(0). This ensures that the newline is processed, avoiding the linked issue
0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.