Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Help with java scanner

  • 18-01-2011 05:24PM
    #1
    Closed Accounts Posts: 2


    hi i need to read a couple lines of text
    for example
    a2 b3 d4
    b4 j5 l8
    and store them

    here it is what i have so far:

    import java.util.Scanner;
    import java.util.ArrayList;
    public class Main {


    public static void main(String[] args) {
    ArrayList<String> CardList = new ArrayList();
    ArrayList<String> ResultList = new ArrayList ();
    String aux;

    Scanner scan = new Scanner(System.in);
    System.out.println("enter number of tests:");
    int Ntests = scan.nextInt();
    for(int i=0; i<Ntests;i++){
    System.out.println("Enter card series");
    aux = scan.next();
    CardList.add(aux);
    }


    }

    }

    the problem is that when i enter "a2 b3 d4" it splits into several strings or something else happens can anyone please help me to mantain the structure and store the whole string into the arraylist thank you


Comments

  • Registered Users, Registered Users 2 Posts: 2,088 ✭✭✭henryporter


    aux = scan.next();

    should be aux = scan.nextLine();


  • Closed Accounts Posts: 2 oz1314


    i have changed it to this:

    public static void main(String[] args) {
    ArrayList<String> CardList = new ArrayList();
    ArrayList<String> ResultList = new ArrayList ();
    String aux;
    String reaux;

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter number of tests:");
    int Ntest = scan.nextInt();
    for(int i=0; i<Ntest;i++){
    System.out.println("Enter card series:");
    reaux = scan.next();
    aux = scan.nextLine();
    CardList.add(aux);
    System.out.println("Stored element:"+CardList.get(i));
    }


    }

    because just using nextLine() skips the line and doesn't let me enter any parameters, this seems to work better except it cuts the first part for example i type "ab dc mb" and it just stores "dc mb", help please.


Advertisement