Jump to content
Banner by ~ Wizard

Need help with java scanner


Gekoncze

Recommended Posts

Hi,

I need some help with java scanner. I have input from file like this:

 

[1] [25] [58] [69] [1] [225] [518] [9] [11] [2] [38] [629]

and need to make output into JTextArea like this:

 

1
25
58
69
1
and so on

 

I could use string tokenizer to do it, but the teacher want us to use scanner for it. What should I use? I tried playing with useDelimiter function, but I have no idea how it works.

 

Here is what I have so far:

 

        // choose file using jfilechooser class
        JFileChooser fch = new JFileChooser();
        fch.showOpenDialog(this);
        File fn = fch.getSelectedFile();
        
        // allocate new array list (declared globally)
        data = new ArrayList<Integer>();
        
        try
        {
            // open file with scanner
            Scanner sc = new Scanner(fn);
            sc.useDelimiter("[]] ");

            while( sc.hasNextInt() )
            {
                data.add( sc.nextInt() );
            }
            
            sc.close();
        }
        catch( Exception e )
        {
            System.out.println("nelze načíst: "+fn.getAbsolutePath()+" "+e.getMessage());
            return;
        }
        
        // write the numbers into text area
        jTextArea1.setText("");
        for( int i = 0; i < data.size(); i++ )
        {
            jTextArea1.append( data.get(i)+"\n" );
        }

 

Can anybody help?

  • Brohoof 1
Link to comment
Share on other sites

I do have to ask, why are you formatting your line like that? if you don't have to, you shouldn't put it like that, if you do, you will have to do more splitting.
 
I would simply do the following:
 

Scanner s = new Scanner(fn);

String content = s.read();
s.close();
StringBuilder sb = new StringBuilder(content);
sb.replace("[", "");
sb.replace("]", "");
String[] almostthere = sb.toString().split(" ");

for(String number : almostther)
{
    data.add(Integer.parseInt(number);
}

Something like that

Also add s.close() perhaps in the finally so your scanner always closes even if an exception is thrown.

 

I hope it makes a little more sense.

Link to comment
Share on other sites

 

 

I do have to ask, why are you formatting your line like that?

Because the teacher formated it that way, so I have to take care of it the way it is.

Well, thanks for the suggestion ^.^ Unfortunetly, we didn't learn string builder... there really isn't a way how to do it using just a plain scanner?

Link to comment
Share on other sites

@@Gekoncze

 

turns out the Scanner class has a skip(String pattern) method so you can first call s.skip("[") then at each nextInt() you can just call skip(] [") until there are no more.

 

Alternatively there is an override for it in the form skip(Pattern pattern). You can use the pattern "[^\D]{1,3}" by making new Pattern(String regular_expression).

 

if you learned how to use it.

  • Brohoof 1
Link to comment
Share on other sites

(edited)

well, so I tried this:


            Scanner sc = new Scanner(fn);
            sc.skip("\\[");

            while( sc.hasNextInt() )
            {
                data.add( sc.nextInt() );
                sc.skip("] \\[");
            }
            
            sc.close();

but it doesn't work (and without the \\ it printed out some error like java unclosed character near index) it doesn't enter the while cycle...

using the pattern is too long

... maybe I'll try the string builder class

Edited by Gekoncze
Link to comment
Share on other sites

(edited)

It works ^.^ I just used something a little bit similar to the string builder, here is the working code

Thanks for your help @@Vaporeon ^.^

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // vbereme soubor pomocí třídy filechooser
        JFileChooser fch = new JFileChooser();
        fch.showOpenDialog(this);
        File fn = fch.getSelectedFile();
        
        // zaalokujeme array list obsahující data
        // zde musíme použít typ Integer (s velkým D), protože array list
        // podporuje pouze třídy a ne vestavěné typy
        // (deklarováno globálně (nahoře před konstruktorem))
        data = new ArrayList<Integer>();
        
        try
        {
            // otevřeme datový proud do souboru pomocí scanneru
            Scanner scan = new Scanner(fn);
            
            // postupně načteme všechny řádky, ze kterých získáváme čísla
            while( scan.hasNextLine() )
            {
                String line = scan.nextLine();
                
                // Z řádku nejprve odebereme všechny závorky, jinak scanner nebude fungovat
                // To uděláme jednoduše tak, že závorky nahradíme mezerou
                line = line.replace( '[', ' ' );
                line = line.replace( ']', ' ' );

                // vytvoříme nový scanner pro řádek, který bude parsovat čísla
                Scanner sc = new Scanner( line );

                // dokud jsou ve scanneru čísla
                while( sc.hasNextInt() )
                {
                    data.add( sc.nextInt() ); // čísla vložíme do array listu
                }
            }

            // uzavřeme soubor
            scan.close();
            
            // vypíšeme data do textového pole
            jTextArea1.setText("");
            for( int i = 0; i < data.size(); i++ )
            {
                jTextArea1.append( data.get(i)+"\n" );
            }
        }
        catch( Exception e )
        {
            System.out.println("nelze načíst: "+fn.getAbsolutePath()+" "+e.getMessage());
        }
    }//GEN-LAST:event_jButton1ActionPerformed
Edited by Gekoncze
  • Brohoof 1
Link to comment
Share on other sites

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // vbereme soubor pomocí třídy filechooser
        JFileChooser fch = new JFileChooser();
        fch.showOpenDialog(this);
        File fn = fch.getSelectedFile();
        
        // zaalokujeme array list obsahující data
        // zde musíme použít typ Integer (s velkým D), protože array list
        // podporuje pouze třídy a ne vestavěné typy
        // (deklarováno globálně (nahoře před konstruktorem))
        data = new ArrayList<Integer>();
        
        try
        {
            // otevřeme datový proud do souboru pomocí scanneru
            Scanner scan = new Scanner(fn);
            
            // postupně načteme všechny řádky, ze kterých získáváme čísla
            while( scan.hasNextLine() )
            {
                String line = scan.nextLine();
                
                // Z řádku nejprve odebereme všechny závorky, jinak scanner nebude fungovat
                // To uděláme jednoduše tak, že závorky nahradíme mezerou
                line = line.replace( '[', ' ' );
                line = line.replace( ']', ' ' );

                // vytvoříme nový scanner pro řádek, který bude parsovat čísla
                Scanner sc = new Scanner( line );

                // dokud jsou ve scanneru čísla
                while( sc.hasNextInt() )
                {
                    data.add( sc.nextInt() ); // čísla vložíme do array listu
                }
            }
        }
        catch( Exception e )
        {
            System.out.println("nelze načíst: "+fn.getAbsolutePath()+" "+e.getMessage());
        }
        finally { scan.close(); }
        // vypíšeme data do textového pole
        jTextArea1.setText("");
        for( int i = 0; i < data.size(); i++ )
        {
            jTextArea1.append( data.get(i)+"\n" );
        }
    }//GEN-LAST:event_jButton1ActionPerformed

 

Changed one thing, adding something within finally like I did, means it will always be executed, even if an exception is thrown, this is in case you need to proceed it doesn't break your program. Closing streams are generally done within finally's.

 

This is in case your piece of code needs to be rerun and your stream isn't left open accidentally.

  • Brohoof 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Join the herd!

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...