0

What I am trying to do is, get input string from user. Add it into arraylist since i have to play with characters later. But first i want to print contents of ArrayList in order to check what is exactly in their. Here is my code

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    List <String> Vowels = new ArrayList<String>();
    System.out.println("What is your string? ");
    String abc = sc.nextLine();
    int n = abc.length();
    for(int i=0; i <= n-1 ; i++)
    {
        Vowels.add(sc.nextLine());
    }

    for(int j=0; j< Vowels.size();j++)
        System.out.println(Vowels.get(j));

}

It is not printing anything or not showing up any error. Your help will be highly appreciated.

3
  • The sc.nextLine() in your for loop is going to block waiting for user input. Your logic is strange as well I think. If you enter the word "wally" then the for loop is going to require you to enter 5 more lines. Is this right? Commented Mar 12, 2014 at 2:40
  • Yes yes.. that is exactly what is happening! 5 more lines! How can I resolve that? Commented Mar 12, 2014 at 2:42
  • try writing proper code. The java program is doing exactly what you are asking it to. It is 100% correct. Commented Mar 12, 2014 at 2:44

2 Answers 2

4

here is your problem:

for(int i=0; i <= n-1 ; i++)
{
    Vowels.add(sc.nextLine());
               ^
}

"It is not printing anything" because it waiting for your input

What you need is:

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    List <String> Vowels = new ArrayList<String>();
    System.out.println("What is your string? ");
    String abc = sc.nextLine();
    int n = abc.length();
    for(int i=0; i < n ; i++)
    {
        Vowels.add(new StringBuilder().append("").append(abc.charAt(i)).toString());
    }

    for(int j=0; j< Vowels.size();j++)
        System.out.print(Vowels.get(j));
}

Input : Burger

Output: Burger

If you want your output as [B, u, r, g, e, r], then just do:

System.out.println(Vowels); //without for loop
Sign up to request clarification or add additional context in comments.

3 Comments

I gave input like "Burger". Its not printing after that. I want it to print [B,U,R,G,E,R] or better "Burger" as it is as input.
@RafaEl It is working now but it is printing as one character per line.. I want to print it as a string. How that can be done?
@GauravK. you want to print it in one line? then just use System.out.print(Vowels.get(j));
0

Based upon your new requirements as in Rafa El's comments, try

abc = "Burger";          // use abc = sc.nextLine();
int n = abc.length();
for(int i=0; i < n ; i++)
{
    Vowels.add("" + abc.charAt(i));
}

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.