Lecture d'un entier au clavier(java)

cs_Yey Messages postés 4 Date d'inscription mercredi 23 mars 2005 Statut Membre Dernière intervention 3 juin 2008 - 23 mars 2005 à 16:03
cs_Yey Messages postés 4 Date d'inscription mercredi 23 mars 2005 Statut Membre Dernière intervention 3 juin 2008 - 23 mars 2005 à 17:36
Bonjour
voila je n'arrive pas a realiser la saisie au clavier d'un entier que je veux exploiter apres pour des choix
(exemple
switch
1 : methode1
2 : methode2
...)

Voila le pg que j'essaie d'utiliser
static int lectureEntier() throws NumberFormatException

{

int cf=-9;
String choix;
choix= null;

try{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
choix= new String();
while(choix==null)
{ choix=br.readLine();
if(choix==null){
br.close();
System.out.println("erreur lecture");
}

}
}

catch(IOException ioe)
{System.out.println("erreur");
}

try
{
{

cf = new Integer(choix).intValue();
}
}

catch(NumberFormatException nfe)
{if(cf==-9){System.out.println("erreur lecture2");}
System.out.println("Vous devez rentrer un entier !");
throw new NumberFormatException();//sans ca le pg ne s'arrete pas
}

return cf;

}

2 réponses

cs_neodante Messages postés 2835 Date d'inscription lundi 11 août 2003 Statut Modérateur Dernière intervention 16 décembre 2006 11
23 mars 2005 à 16:42
Salut

Si tu veux convertir une chaine vers un entier : Integer.parseInt et ensuite intValue() pour récupérer ton int ... cela devrait t'aider à faire ton switch non ??? ;-)
@+
0
cs_Yey Messages postés 4 Date d'inscription mercredi 23 mars 2005 Statut Membre Dernière intervention 3 juin 2008
23 mars 2005 à 17:36
Bonjour et merci neodante.
desole mais j'y arrive toujours pas. J'ai un problème avec la NumberFormatException.

voici le nouveau code:
static int lectureEntier() throws NumberFormatException

{
String choix;//= new String();
choix= null;
Integer cf;
int ch= -9;
try{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
choix= new String();

while(choix==null)
{ choix=br.readLine();
if(choix==null)
{System.out.println("erreur lecture");}
}
}

catch(IOException ioe)
{System.out.println("erreur");}

try{cf= new Integer(Integer.parseInt(choix)); }

catch(NumberFormatException nfe)
{System.out.println("Vous devez rentrer un entier !");
// throw new NumberFormatException();//sans ca le pg ne s'arrete pas
}
ch= cf.intValue();
return ch;
}

merci d'avance
0
Rejoignez-nous