-2

I want to take string as an input from user until "#" is the input i.e a series of string (all in different lines) till "#" is found and store the strings in an arraylist of type string. I wrote this code in JAVA but it's not working as required.

import java.util.ArrayList; import java.util.Scanner;

public class wordMetaMorphism {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    ArrayList<String> input = new ArrayList<String>();

    while(!(sc.next().equals("#"))) {
        String s = sc.next();
        input.add(s);
    }
    System.out.println(input);
}

}

and i am getting this output where only the alternate strings are getting stored. I also tried sc.nextLine() but it is all same.

input - dip lip mad map maple may pad pip pod pop sap sip slice slick spice stick stock # #

output - [lip, map, may, pip, pop, sip, slick, stick, #]

  • `sc.next()` gets the next token. Every time you call it. Not the one you just read in the previous call to `sc.next()`. Variables are your friends. – JB Nizet Nov 30 '19 at 12:04

3 Answers3

-1

You are calling sc.next() and checking if that line is equal to "#", then reading the next token. This is causing it to occur with every alternate token.

You could do this:

String token = "";
while(!((token = sc.next()).equals("#")))input.add(token);

instead of the while loop you have.

Ananay Gupta
  • 355
  • 3
  • 14
-1
import java.util.ArrayList; import java.util.Scanner;

public class wordMetaMorphism {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    ArrayList<String> input = new ArrayList<String>();

    while(sc.hasNext()) {
        String s = sc.next();
        if(s.equals("#")) break;
        input.add(s);
    }
    System.out.println(input);
}

}
Ankit Agrawal
  • 596
  • 5
  • 12
-1

i have modified your code please check below

import java.util.ArrayList;
import java.util.Scanner;

public class wordMetaMorphism {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<String> input = new ArrayList<String>();
        String s = sc.next();
        while(!(s.equals("#"))) {
            input.add(s);
            s = sc.next();
        }
        System.out.println(input);
    }
}
prasad
  • 1,277
  • 2
  • 16
  • 39