Salve,
ho scritto il codice che segue, composto dalla definizione di un oggetto mytoken che riceve una stringa e restituisce delle mini-stringhe che crea a partire dalla stringa iniziale.
I token vengono creati a partire da un identificatore che viene definito nel cotruttore.
Nel main lo scopo è di utilizzare l'oggetto per poter eseguire una somma tra numeri dati tramite una stringa.
Il token funziona (l'ho provato con un altro main che per adesso è chiamato main1) mentre non capisco dove si blocca nel fare le somme (credo che il problema sia nella permanenza del ciclo while).
Ben accetti anche consigli per ottimizzare il codice![]()
codice:import java.io.*; public class mytoken { String a; char ch; int rimanente; boolean ctrl = true; mytoken(String f, char se) { a = f; ch = se; } public String nextToken() { char tmp ='a'; ctrl=true; String token = new String(); while (ctrl) { if (rimanente == a.length()) { ctrl = false; break; } else { tmp = a.charAt(rimanente); if (tmp != ch) { token = (token+String.valueOf(tmp)); //System.out.println(rimanente); ctrl = true; } else { ctrl=false; } rimanente++; } } return token; } public static void main(String[] args) { int somma=0; BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); String a = new String(); try{a=buff.readLine();}catch(IOException e){}; mytoken numeri = new mytoken(a,' '); while (numeri.ctrl) { String tmp = numeri.nextToken(); somma = somma + Integer.parseInt(tmp); } System.out.println(somma); } public static void main1(String[] args) { BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); String a = new String(); String a1S = new String(); String n = "a"; String termina = "basta"; try{a=buff.readLine();}catch(IOException e){}; char b = ' '; char tmp='0'; mytoken tok = new mytoken(a,b); boolean turno = true; System.out.println("Per richiamare la parola successiva scrivi \"a\""); while(turno) { try{a1S=buff.readLine();}catch(IOException e){}; tmp = a1S.charAt(0); if (tmp == 'a' & (tok.rimanente < a.length())) { String tokenS = tok.nextToken(); System.out.println(tokenS); } else { turno = false; } } } }


Rispondi quotando