0% found this document useful (0 votes)
20 views9 pages

Java InputMismatchException Handling

The document contains code examples for 5 Java exercises: 1. Inserting a value into an array at a given index and handling exceptions. 2. Defining a Date class that checks for valid dates and handles exceptions. 3. Defining Student and Note classes to calculate student averages, handling exceptions. 4. Defining a Keyboard class to get integer input from the user and handle exceptions. 5. The code shows how to use exceptions and exception handling in different contexts.

Uploaded by

Chayma Saad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views9 pages

Java InputMismatchException Handling

The document contains code examples for 5 Java exercises: 1. Inserting a value into an array at a given index and handling exceptions. 2. Defining a Date class that checks for valid dates and handles exceptions. 3. Defining Student and Note classes to calculate student averages, handling exceptions. 4. Defining a Keyboard class to get integer input from the user and handle exceptions. 5. The code shows how to use exceptions and exception handling in different contexts.

Uploaded by

Chayma Saad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chaima saad / TP10

Compte-rendu Java
Exercice 3 :
//class ex3
package ex3;
import [Link];
import [Link];
public class ex3 {

public static void method() {


int t[]=new int[5];
t[0]=2;
t[1]=5;
t[2]=8;
t[3]=1;
t[4]=3;

try
{
[Link]("entrer V");
Scanner vv=new Scanner([Link]);
int v=[Link]();

[Link]("entrer indice ");


Scanner ind=new Scanner([Link]);
int in=[Link]();

int i;
for(i=[Link];i>in;i--)
{
t[i]=t[i-1];
}
t[in]=v;
}
catch(ArrayIndexOutOfBoundsException e)
Chaima saad / TP10

{
[Link]("taille de tableau !:"
+[Link]()););
}
catch(InputMismatchException a)
{
[Link]("il faut entrer un entier !:" +
[Link]());
}

}
}

//class testEx3
package ex3;
public class testEx3
{
public static void main(String[] args)
{
[Link]();
}

Exercice 4 :
//class date
package ex4;
import [Link];
import [Link];
public class date {
private int jour,mois,annees;
int nombrejour()
{
if(mois==1 || mois==3 || mois==5 || mois==7 ||
mois==8 || mois==10 || mois==12)
return 31;
Chaima saad / TP10

else if(mois==4 || mois==6 || mois==9 || mois==11)


return 30;
else if(mois==2)
{ if(annees%4==0)
return 29;
else
return 28;}
else return 0;

}
public date()
{
Scanner x=new Scanner([Link]);

try {
[Link]("entrer l'année :");
int a=[Link]();

[Link]("entrer le mois");
int m=[Link]();

[Link]("entrer le jour");
int j=[Link]();

[Link]=j;
[Link]=m;
[Link]=a;

if([Link]<0 || [Link]>[Link]() ||
[Link]>12 || [Link]<0 && [Link]<0)
{
throw new DateInvalideException();
}
}
catch(DateInvalideException e)
{
[Link]([Link]());
}
catch(InputMismatchException i)
{
Chaima saad / TP10

[Link]("Erreur: n'est pas un


entier !!");
}
}

//class DateInvalideException
package ex4;
public class DateInvalideException extends Exception{
public DateInvalideException() {
super("Date invalide");
}
public DateInvalideException(String message)
{
super(message);
}
}

//class testDate
package ex4;
public class testDate {

public static void main(String[] args) {


date d=new date();

}
Exercice 5.1 :
//class etudiant
package ex5_1;
public class etudiant {
String nom;
String prenom;
String idUnique;
Chaima saad / TP10

note notes[]=new note[3];


etudiant(String n,String p,String i,note[] not)
{
[Link]=n;
[Link]=p;
[Link]=i;
[Link]=not;

public void moyenne()


{
double nb=0;
note a;
int i;
double x,moy;
double sm=0;
try {
for(i=0;i<10;i++)
{

x=notes[i].val;
nb=nb+notes[i].coff;
sm=sm+x;
}
moy= sm/nb;
[Link]("la moyenne est :"+moy);
}
catch(NullPointerException e)
{
[Link]([Link]());
}
catch(ArithmeticException e)
{

[Link]([Link]());
}

}
}
Chaima saad / TP10

//class note
package ex5_1;
import [Link];
import [Link];

public class note {

String en;
int coff;
double val;
note(String e,double v,int c)
{
[Link]=e;
[Link]=v;
[Link]=c;
}

public static note ajoutNote()


{

Scanner s=new Scanner([Link]);


[Link]("entrer l'enseignante:");
String e=[Link]();

[Link]("entrer la valeur de note :");


double v=[Link]();

[Link]("entrer la coffecient de note :");


int c=[Link]();

note no=new note(e,v,c);


return no;

//class testEx5_1
Chaima saad / TP10

package ex5_1;

import [Link];
import [Link];
public class testEx5_1 {
public static void main(String[] args)
{
note notes[]=new note[10];
try {
Scanner s=new Scanner([Link]);
[Link]("entrer le nom :");
String nom=[Link]();

[Link]("entrer le prenom :");


String prenom=[Link]();

[Link]("entrer l'identifiant unique :");


String id=[Link]();

int i;
for(i=0;i<1;i++)
{

notes[i]=[Link]();

etudiant e1=new etudiant(nom,prenom,id,notes);

[Link]();
}
catch(InputMismatchException e)
{[Link]([Link]());}
}

Exercice 5.2 :
Chaima saad / TP10

//class Clavier

package ex5_2;
import [Link];
import [Link];
public class Clavier {
public Clavier() {

try
{
Scanner sc =new Scanner([Link]);
[Link]("donner une ligne
d'information de type int ");
int a=[Link]();

}
catch(InputMismatchException e)
{
[Link]("ce n'est pas un
entier:"+[Link]());

}
catch(Exception e)

{
[Link]("Erreur: "+[Link]());
}
}

}
//class testClavier
package ex5_2;
public class TestClavier {
public static void main(String[] args)
{
while(true)
{
Clavier x=new Clavier();
Chaima saad / TP10

}
}

Common questions

Powered by AI

The `ex3` class specifically handles `ArrayIndexOutOfBoundsException` and `InputMismatchException`, providing precise feedback for these errors: it addresses array size issues and non-integer inputs respectively. In contrast, the `Clavier` class in `ex5_2` handles `InputMismatchException` for non-integer inputs but includes a general `Exception` catch block for any other unforeseen errors, which provides less targeted feedback. This broader handling in `ex5_2` can capture diverse errors but may obscure specific issues .

The `Clavier` class handles user input by prompting the user to enter a line of information that is expected to be of type `int`. It uses a `try-catch` block to handle exceptions. Specifically, it catches `InputMismatchException` if the input is not an integer, displaying a message "ce n'est pas un entier" along with the exception message. Additionally, it includes a general `Exception` catch block to handle any other unanticipated exceptions, displaying a generic error message .

The `testEx5_1` class utilizes a `try-catch` block to manage `InputMismatchException`, which is effectively used to capture situations where user inputs do not match expected data types during creation of `etudiant` objects and note addition. However, the mechanism's effectiveness is limited as it does not handle other possible exceptions, such as `NullPointerException` or issues resulting from invalid array indices. Enhanced exception handling would involve broader checks or validations to ensure data integrity and program robustness .

The `etudiant` class uses the `moyenne` method to calculate a student's average grade by iterating over an array of `note` objects and summing up the products of grades and their respective coefficients, then dividing by the total sum of coefficients. Potential issues during execution include `NullPointerException` if any `note` object in the array is `null`, or `ArithmeticException` if the total sum of coefficients `nb` is zero, leading to division by zero. These exceptions are caught and their messages displayed, ensuring the program does not crash .

The program manages invalid dates in the `date` class by employing a custom exception named `DateInvalideException`. During date initialization, it checks whether the input day is within the permissible range for the given month, whether the month is between 1 and 12, and whether the year is positive. If any of these conditions are false, a `DateInvalideException` is thrown with the message "Date invalide." This prevents the creation of invalid dates and informs the user of errors in the input .

Using hardcoded values in the array manipulation code in the `ex3` class can lead to inflexibility, limiting the ability to handle arrays of varying sizes, and increasing the risk of index errors if the length of the array changes. A more robust approach would be to use dynamic data structures like lists that grow automatically as elements are added. Additionally, validating array index bounds before attempting to insert an element would prevent potential `ArrayIndexOutOfBoundsException` .

The logic for shifting elements in the `ex3` class involves iterating backwards from the end of the array to the specified index and copying each element to the next higher index position to make room for a new element. A potential pitfall of this approach is that it does not check whether the array has sufficient space to accommodate the new element, leading to an `ArrayIndexOutOfBoundsException`. Moreover, this method can be inefficient for large arrays as it requires shifting multiple elements, which could degrade performance .

The `note` class adds new notes through the static method `ajoutNote`, which prompts the user to input the note's name, value, and coefficient. Input is obtained using a `Scanner` object. Issues related to user input include the potential for `InputMismatchException` if the entered values for `double` or `int` are incorrect types. The input process assumes all user input is correct, lacking validation, which could lead to logic errors if incorrect data types are entered .

The `date` class determines the number of days in a month using the `nombrejour` method. It checks if the month is one with 31 days (January, March, May, etc.), 30 days (April, June, September, November), or February. For February, it further checks if the year is a leap year by seeing if the year is divisible by 4. If it is, February is considered to have 29 days; otherwise, it has 28 days. If any month lies outside known bounds, it returns 0 .

The `method` in the `ex3` class is designed to modify an integer array `t` by inserting a user-provided value at a specific index while shifting other elements. It uses a `try-catch` block to handle two types of exceptions: `ArrayIndexOutOfBoundsException`, which is thrown if the user attempts to access an array index outside its bounds, and `InputMismatchException`, which is caught if the user inputs a non-integer value. This ensures the program does not crash and provides informative messages to the user, such as array size errors or integer entry requirements .

You might also like