Gekoncze 327 May 7, 2013 Share May 7, 2013 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? 1 Link to comment Share on other sites More sharing options...
Killian Jones 2,655 May 7, 2013 Share May 7, 2013 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 thatAlso 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 More sharing options...
Gekoncze 327 May 7, 2013 Author Share May 7, 2013 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 More sharing options...
Killian Jones 2,655 May 7, 2013 Share May 7, 2013 @@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. 1 Link to comment Share on other sites More sharing options...
Gekoncze 327 May 8, 2013 Author Share May 8, 2013 (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 May 8, 2013 by Gekoncze Link to comment Share on other sites More sharing options...
Gekoncze 327 May 9, 2013 Author Share May 9, 2013 (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 May 9, 2013 by Gekoncze 1 Link to comment Share on other sites More sharing options...
Killian Jones 2,655 May 9, 2013 Share May 9, 2013 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. 1 Link to comment Share on other sites More sharing options...
Recommended Posts
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