|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Junior Member
Iscritto dal: Sep 2011
Messaggi: 1
|
[java] Problema con java e file di testo
Buonasera a tutti...
ho un file di testo composto da piu righe ed ogni riga è composta da: stringa valore_intero stringa io dovrei fare la somma sei vari valori interi presenti nelle varie righe ma non sò come estrarli ![]() qualcuno di voi può gentilmente darmi una mano? ![]() allego il codice: import java.io.*; import java.util.*; class tl { public static void main(String [] args) { int somma=0; String s; try { BufferedReader in=new BufferedReader (new FileReader("testo.txt")); s=in.readLine(); while(s!=null) { StringTokenizer st = new StringTokenizer(s, " "); System.out.println(s); if(sc.hasNextInt()) somma=sc.nextInt(); System.out.println("Intero: "+ somma); s=in.readLine(); } } catch(FileNotFoundException e) { System.out.println("Errore apertura file testo"); System.out.println(0); } catch(IOException e) { System.out.println("Errore I/O file"); System.out.println(0); } } } |
![]() |
![]() |
![]() |
#2 |
Senior Member
Iscritto dal: Jan 2007
Messaggi: 2267
|
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. Fonte:http://download.oracle.com/javase/6/docs/api/
Quindi dovresti provare ad usare le funzionalità di String invece di StringTokenizer. Prova questo: Codice:
package example; import java.io.*; public class Main { public static void main(String[] args) { int somma = 0; File file = new File("Prova.txt"); try{ DataInputStream istream = new DataInputStream(new FileInputStream(file)); byte[] raw_bytes = new byte[(int)file.length()]; istream.read(raw_bytes,0,(int)file.length()); istream.close(); String s = new String(raw_bytes); String[] tokens = s.split("[ \t\n]"); int i = 1; while(i<=tokens.length){ somma += Integer.parseInt(tokens[i]); i += 3; } System.out.println(somma); }catch(Exception e){System.out.println(e.getMessage());System.exit(-1);} } } Codice:
5 1 come va 4 100 te 5 11
__________________
Concluso con:... Ultima modifica di Floris : 16-09-2011 alle 06:22. |
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 04:23.