como manejar Esta excepción aqui... ? suma simple

Iniciado por rub'n, 28 Noviembre 2010, 19:23 PM

0 Miembros y 2 Visitantes están viendo este tema.

rub'n

Como manejo esta excepcion aqui ,,,   para controlar que el usuario no introduzca una letra

saludos!!!

Código (java) [Seleccionar]
import java.io.*;
public class Suma {

public static void main(String[] args) throws Exception{
  BufferedReader leer = new BufferedReader(new InputStreamReader(System.in));
int n=0,suma=0,k=1;

try{
System.out.println("introduce numero, y -1 para Finalizar: ");
n=Integer.parseInt(leer.readLine());
}
catch(Exception e){
System.out.println("introduce un valor numerico por favor ");
}

while(n != -1 ) {

suma+=n;

System.out.println("introduce valor, y -1 para Finalizar: ");
try{
n=Integer.parseInt(leer.readLine());
}
catch(Exception e){
System.out.println("introduce un valor numerico por favor");

}
}k++;

System.out.println("La suma es: "+suma);

}

}


introduce numero, y -1 para Finalizar
5
introduce valor, y -1 para Finalizar
a
introduce un valor numerico por favor
introduce valor, y -1 para Finalizar
-1
La suma es: 10


rubn0x52.com KNOWLEDGE  SHOULD BE FREE!!!
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen

Afsoon

Es una idea descabellada hay mas simples pero es la primera que se me ha pasado por la cabeza xD no me apetece pensar mucho que la necesito para los examenes XD, pero esta forma es la chapuza ya que le falta dar toques pero hay tienes un ejemplo de saber si es una letra o no

Código (java) [Seleccionar]

int n=0,suma=0,k=1;
String[] letras = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","ñ","o","p","q","r","s","t","u","v","w","x","y","z"};

System.out.println("introduce numero, y -1 para Finalizar: ");
n=Integer.parseInt(leer.readLine());
for(int a=0; a<=letras.lenght; a++)
{
if(n == letras[a]){
System.out.println("Inserte un número no una letra");
System.exit(0);
}

}


Te aconsejo no usar este metodo hay que darle muchos toques pero es un ejemplo es que no tengo mucho tiempo sino te haría uno en condiciones

rub'n



rubn0x52.com KNOWLEDGE  SHOULD BE FREE!!!
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen

Leyer

#3
No estaras buscando algo asi sin usar try y catch

Código (java) [Seleccionar]
import java.util.Scanner;
public class Suma {
public static void main(String[] args) {
int n=0,suma=0;
Scanner scanner=new Scanner(System.in);
do{
suma+=n;
System.out.println("introduce valor, y -1 para Finalizar: ");
if(scanner.hasNextInt())n=scanner.nextInt();
else{
if(scanner.hasNext())scanner.next();
System.out.println("introduce un valor numerico por favor\n");
}
}while(n!=-1);
System.out.println("La suma es: "+suma);
}
}

Shell Root

Hasta con ExpReg se puede,
Código (java) [Seleccionar]
  public static void sValidateNumbers(String sString){
    Pattern sPattern = Pattern.compile("^[0-9]*$");
    Matcher sMatcher = sPattern.matcher(sString);

    if ( !sMatcher.find() ){ System.out.println("NO, son numeros.\n"); }
    else{ System.out.println("SI, son numeros.\n"); }
  }
Por eso no duermo, por si tras mi ventana hay un cuervo. Cuelgo de hilos sueltos sabiendo que hay veneno en el aire.

rub'n



rubn0x52.com KNOWLEDGE  SHOULD BE FREE!!!
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen

1mpuls0

Hay por lo menos 10 maneras diferentes de hacerlo.

Código (java) [Seleccionar]

               do {
System.out.println("introduce numero, y -1 para Finalizar: ");
num = leer.readLine();
}while(!isNumeric(num));
n=Integer.parseInt(num);


Métedo que usa el código de arriba.
Código (java) [Seleccionar]

private static boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
}
catch(Exception e) {
return false;
}
}



Usando banderas
Código (java) [Seleccionar]

boolean status = false;
do {
try{
System.out.println("introduce numero, y -1 para Finalizar: ");
n=Integer.parseInt(leer.readLine());
status=true;
}
catch(Exception e) {
status=false;
}
}while(status==false);



Usando otro método
Código (java) [Seleccionar]

do {
System.out.println("introduce numero, y -1 para Finalizar: ");
str = leer.readLine();
}while(isLetter(str));
n=Integer.parseInt(str);


Método del código de arriba
Código (java) [Seleccionar]

private static boolean isLetter(String string) {
if(string.matches("[a-zA-Z]"))
    return true;
    else
    return false;
}



Sin usar método ni try catch
Código (java) [Seleccionar]

String str="";
do {
System.out.println("introduce numero, y -1 para Finalizar: ");
str = leer.readLine();
}while(str.matches("[a-zA-Z]"));


Un saludo.
abc

rub'n



rubn0x52.com KNOWLEDGE  SHOULD BE FREE!!!
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen