PDA

View Full Version : [Java] Problema con un Delimiter di uno Scanner


caurusapulus
18-06-2008, 11:34
Salve ragazzi! Ipotizzando di dover leggere con uno Scanner da un File un oggetto composto da: int:int:int-int:int avevo pensato di fare una cosa così:

public static Object read(Scanner s) throws Exception{
if(s.hasNextLine()){
int giorno_ = s.useDelimiter(":").nextInt();
int mese_ = s.useDelimiter(":").nextInt();
int anno_ = s.useDelimiter("-").nextInt();
int ora_ = s.useDelimiter(":").nextInt();
int minuto_ = s.nextInt();
if(s.hasNextLine()) s.nextLine();
return new Object(giorno_,mese_,anno_,ora_,minuto_);
}
else return null;
}


Andando però a vedere, purtroppo lo Scanner non mi prende il Delimiter("-")!

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Object.read(Object.java:42)
at Main.main(Main.java:12)

Object.java:42 è la linea int anno_ = s.useDelimiter("-").nextInt();

Come posso risolvere? :help:

Angus
18-06-2008, 12:17
quell'eccezione viene lanciata in realtà da .nextInt()

ti conviene quindi controllare che il contenuto del file sia corretto

caurusapulus
18-06-2008, 13:41
Uhm.... :confused:
Il file è fatto solamente da numeri interi (ad esempio: 10:04:2008-10:30)
Se provo a mettere al posto del "-" nuovamente i ":" non ho problemi :cry:

renaulto
19-06-2008, 03:05
public static Oggetto read(String s) {
String[] tokens = s.split(":|-");
return new Oggetto (tokens[0],tokens[1],tokens[2],tokens[3],tokens[4]);
}