|
|
Continuazione dell'esercizio: "Dati n reali inseriti dall'utente calcolarne la media" import javax.swing.JOptionPane;
public class Eccezioni10
{
public static void main(String args[])
{
String input;
double v[]=new double[5];
try
{
input=JOptionPane.showInputDialog("Quanti elementi?");
int numElementi=Integer.parseInt(input);
double somma=0;
for(int i=0; i < numElementi; i++)
{
input=JOptionPane.showInputDialog("v["+i+"]=");
v[i]=Double.parseDouble(input);
somma+=v[i];
}
JOptionPane.showMessageDialog(null, "Media=" + dividi(somma, numElementi));
}
catch(ArrayIndexOutOfBoundsException ex)
{
JOptionPane.showMessageDialog(null, "Numero elementi eccessivo");
}
catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "Input errato");
}
}
public static double dividi(double x, double y)
{
if(y==0)
throw new ArithmeticException("Divisione per zero!");
else
return x/y;
}
}
Nel metodo dividi() potrebbe essere lanciata un'eccezione throw new ArithmeticException(); oppure throw new ArithmeticException("Divisione per zero!");
che provocherebbe l'interruzione dell'esecuzione, è meglio delegare alla sua cattura il metodo chiamante import javax.swing.JOptionPane;
public class Eccezioni11
{
public static void main(String args[])
{
String input;
double v[]=new double[5];
try
{
input=JOptionPane.showInputDialog("Quanti elementi?");
int numElementi=Integer.parseInt(input);
double somma=0;
for(int i=0; i < numElementi; i++)
{
input=JOptionPane.showInputDialog("v["+i+"]=");
v[i]=Double.parseDouble(input);
somma+=v[i];
}
JOptionPane.showMessageDialog(null, "Media="+dividi(somma, numElementi));
}
catch(ArrayIndexOutOfBoundsException ex)
{
JOptionPane.showMessageDialog(null, "Numero elementi eccessivo");
}
catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "Input errato");
}
catch(ArithmeticException ex) (3)
{
JOptionPane.showMessageDialog(null, "Attento: " + ex.getMessage());
}
}
public static double dividi(double x, double y) throws ArithmeticException (2)
{
if(y==0)
throw new ArithmeticException("Divisione per zero!"); (1)
else
return x/y;
}
}
|
|