2

The text file contains the following data. I wish to remove the '$' from each row of the text file. I also wish to store the Name,Drink and Cost in variables for future manipulation. However, that can be performed later. I do not understand what is wrong with my code, Here is the Textfile Data:

Problem solved using Regex escape pattern. I had to replace the "$" with "\s*\$\s*"

Rubin$Vodka$55
Alex$Gin$22
Max$Water$FREE

Code:

  File filename = new File("animals2.txt");        
        try{
        Scanner sc = new Scanner(filename);
        String line = sc.nextLine();
        Scanner linesc = new Scanner(line).useDelimiter("$");

        while(linesc.hasNext()){
            String name = linesc.next();
            txaDisplay.append(name + "\n");

        }
    }
    catch(Exception e){
                    e.printStackTrace();
    }
Ryan Teller
  • 33
  • 1
  • 6
  • What is exactly your question? – Pau Oct 17 '16 at 10:58
  • 4
    Possible duplicate of [How do I use a delimiter in Java Scanner?](http://stackoverflow.com/questions/28766377/how-do-i-use-a-delimiter-in-java-scanner) – AxelH Oct 17 '16 at 10:59
  • I do not understand why my code does not work – Ryan Teller Oct 17 '16 at 11:06
  • You had your answer but the idea is to read how useDelimeter work. This is well explain in the duplicated question. The parameter is a regex, `$` is a special character. – AxelH Oct 17 '16 at 11:22

7 Answers7

4

Simply change this line of code:

 Scanner linesc = new Scanner(line).useDelimiter("\\s*\\$\\s*");

You need to pass a regular expression pattern escaping the $ sign.

Daniele
  • 1,102
  • 1
  • 11
  • 24
1

You can try this..

File filename = new File("animals2.txt");        
    try{
    Scanner sc = new Scanner(filename);

    while(sc.hasNext())
    {
        StringBuffer txaDisplay = new StringBuffer();
         String line = sc.nextLine();
         StringTokenizer linesc = new StringTokenizer(line,"/($)/g");

         while(linesc.hasMoreElements()){
            String name = linesc.nextToken();
            txaDisplay.append(name+" ");
         }
         System.out.println(txaDisplay);
    }
  }
  catch(Exception e){
    e.printStackTrace();
  }
Vikas Jaiswal
  • 66
  • 1
  • 4
0

Use the split method of the String. You cannot accomplish what you are trying with Scanner.

public static void main( String[] args)
{
    File filename = new File( "animals2.txt");

    try{
        Scanner sc = new Scanner( filename);

        while( sc.hasNextLine())
        {
            String line = sc.nextLine();
            String[] arr = line.split( "\\$");

            for( String str : arr)
            {
                txaDisplay.append( str + "\n");
            }
        }
    } catch( Exception e) {
        e.printStackTrace();
    }
}

As a side note, do not use StringTokenizer. Here is what the documentation says:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

uoyilmaz
  • 2,855
  • 11
  • 25
0

Try this

        try {
        File file = new File("animals2.txt");
        List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
        for(String s: lines)
        {
            String str[] = s.split("$");
            for(int i = 0; i < str.length; i++)
            {
                 txaDisplay.append(str[i] + "\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
Sasikumar Murugesan
  • 4,056
  • 9
  • 47
  • 70
0

If you can, use Guava's Splitter.

File filename = new File("animals2.txt");
final Splitter dollarSplitter = Splitter.on('$'); // checks for the char, not the regex.
try (Scanner sc = new Scanner(filename)) {
  String line = sc.nextLine();
  for (String name: dollarSplitter.split(line)) {
    txaDisplay.append(name + "\n");
  }
} catch(Exception e) {
  e.printStackTrace();
}
Olivier Grégoire
  • 28,397
  • 21
  • 84
  • 121
0

Here is how you need to do to loop correctly on each line using the delimiter correctly: (based on your code)

Scanner sc = null, scLine = null;
    try{
        sc = new Scanner(new File("./test.txt")); //CHANGE THE FILE HERE

        String s;
        while(sc.hasNext()){
            scLine = new Scanner(sc.nextLine());
            scLine.useDelimiter("\\$");
            while(scLine.hasNext()){
                s = scLine.next();
                System.out.println(">" + s); //HERE YOU NEED TO APPEND INTO YOUR INSTANCE
            }
            System.out.println("#"); //AND REMOVE THIS LINE. I WORKED IN CONSOLE TO TEST THIS
            scLine.close();
        }
        sc.close();
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        if(scLine != null) scLine.close();
        if(sc != null) sc.close();
    }

The first loop is design to read EVERY line of the file. For each line, you use a Scanner that will use the regex to split the line based on the $ sign.

This could be done with the String.split("") methods but I kept your design here. (Split use a regex but remove empty cell on the beginning and on the end).

And of course, you need to close every scanner correctly. So during the loops and in the finally in case of an exception.

AxelH
  • 13,322
  • 2
  • 21
  • 50
-2
String[] parts = line.split("$");
String name = parts[0];
String alcohol = parts[1];
String price = parts[2];
Alex Klimashevsky
  • 2,307
  • 3
  • 22
  • 51
  • @AxelH of cause. you need to think about corner cases yourself – Alex Klimashevsky Oct 17 '16 at 11:08
  • Well, nothing warns him that the split methods trim the empty cells (except the doc)... so he might be stuck a long time before he understand that. And since you did not explain anything... well this is not a good answer. – AxelH Oct 17 '16 at 11:12