You are on page 1of 9

//Hutanu_Paul_2031_Lab6

//
1. Enter from the keyboard some pairs of numerical values (int, float, e
tc.) and try to divide the first number by the second value.
//Display the result. What s the difference between dividing integer or real numbe
rs? Catch the ArithmeticException generated if the second number is zero
//(using a throw instruction). In the catch module, change the value of the divi
der to an implicit value, different than zero. Redo the division, display the ne
w
//result and the new value of the divider.
//
Rewrite the code by considering a method named divide() that throws a ma
thematical exception if a zero division is about to occur.
//In the main method, catch the thrown exception.
package myPackagelab6;
public class MainClass {
public static void main(String[] args) {
int a = 1, b = 0;
double c = 1.1, d = 0.0;
try {
System.out.println(a / b);
System.out.println(c / d);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by 0!\n");
// e.printStackTrace();
b = 1;
d = 1.1;
}
System.out.println(a + " / " + b + " = " + a / b);
System.out.println(c + " / " + d + " = " + c / d);
}
}
//
2. Define an exception class derived from a specific exception-type base
class that is supposed to handle unusual string to number conversions. Use this
//class for monitoring a code sequence that belongs to the main() function, read
s a non-numeric String variable from the keyboard and after that, the code tries
//to convert the String input into an integer value. Display the stack trace rel
ated to that exception.
package myPackagelab6;
public class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}
package myPackagelab6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainClass {

public static void main(String[] args) {


String s = null;
BufferedReader in = new BufferedReader(new InputStreamReader(Sys
tem.in));
System.out.println("Enter the number: ");
try {
s = in.readLine();
} catch (IOException ioe) {
}
int b = 0;
try {
b = convertToInt(s);
System.out.println(b);
} catch (MyException me) {
me.printStackTrace();
}
}
private static int convertToInt(String s) throws MyException {
int rez = 0;
try {
rez = Integer.parseInt(s);
} catch (Exception ex) {
throw new MyException("EROARE la conversie!");
}
return rez;
}
}
//
3. Write a Java application that implements a block of code capable of t
hrowing arithmetic exceptions, I/O exceptions, array indexing exceptions or any
//other type of exception. Display significant messages in each specific catch b
lock. Pay attention to the order in which the catch blocks are implemented.
//Move the suspicious block of code inside a method and rewrite the exceptions h
andling mechanism.
package myPackagelab6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainClass {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(Sys
tem.in));
int n = 0, index = 0;
System.out.println("Enter the numeber of elements: ");
try {
n = Integer.parseInt(in.readLine());
} catch (IOException ioe) {
System.out.println(ioe.toString());
System.exit(1);
}
int[] a = new int[n];
System.out.println("Enter the elements of the array: ");
try {
for (int i = 0; i < a.length; i++) {

System.out.print("a[" + i + "]=");
a[i] = Integer.parseInt(in.readLine());
}
System.out.println("The index of the value is: ");
index = Integer.parseInt(in.readLine());
System.out.println("The element requested is: " + a[inde
x]);
System.out.println("The division of the first two elemen
ts is: "
+ a[0] / a[1]);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NumberFormatException nfex) {
System.out.println("ERROR 1!!!");
nfex.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ERROR 2!!!");
e.printStackTrace();
} catch (ArithmeticException e) {
System.out.println("ERROR 3!!!");
e.printStackTrace();
}
}
}

//
4. Write a Java application that defines a class with an array of String
s (some students names) as a private attribute. The number of elements in the
//array is predefined and has the value 20. The actual number of names is detemi
ned from a keyboard reading process (a confirmation is needed for continuing).
//Implement a sorting algorithm that is supposed to order the names in an alphab
etical manner. The algorithm processes the maximum number of elements
//(20 positions). Handle the exceptions produced by trying to access some inexis
tent elements.
package myPackagelab6;
public class Student {
private String name;
Student() {
}
Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package myPackagelab6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainClass {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(Sys
tem.in));
Student[] lista = new Student[20];
int n = 0;
char ch = ' ';
for (int i = 0; i < 20; i++) {
System.out.print("Do you wish do add anothe student (Y/N
): ");
try {
ch = in.readLine().charAt(0);
} catch (IOException e) {
e.printStackTrace();
}
if (ch != 'N') {
System.out.print("Write the name of the student:
");
try {
lista[n++] = new Student(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
} else
break;
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if ((lista[i].getName().charAt(0)) > (lista[j].g
etName()
.charAt(0))) {
Student temp = new Student();
temp = lista[i];
lista[i] = lista[j];
lista[j] = temp;
}
}
}
System.out.println("The sorted list:");
for (int i = 0; i < n + 1; i++) {
try {
System.out.println(lista[i].getName());
} catch (NullPointerException e) {
System.out.print("The index you enter does not e
xist");
}
}
}
}

//
5. Define a method that returnes a randomly generated letter. The method
receives as parameter an integer variabile with the following possible values:
//1 => a vowel is requested, 2 => a consonant is needed, 3 => any letter type wi

ll do. The method throws a specific exception if the generated letter doesn t
//match the desired type.
//
Use the method described above for generating an array of characters wit
h the length specified by the user.
//The filling rule is: vowel, 1 consonant, vowel, 2 consonants, etc. In the exce
ption handling block, replace the wrong characters with * .
package myPackagelab6;
@SuppressWarnings("serial")
public class MyException extends Exception {
MyException(String msg){
super(msg);
}
}
package myPackagelab6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Generate {
String vowel = "aeiou";
boolean isVowel(char
boolean ok =
for (int i =
ok =
return ok;
}

x) {
false;
0; i < vowel.length(); i++)
x == vowel.charAt(i) ? true : ok;

public char generateChar() {


Random r = new Random();
return (char) (r.nextInt(26) + 'a');
}
public char genVowel() throws MyException {
char c = generateChar();
if (!isVowel(c))
throw new MyException(c + " is not is not a vowel!");
return c;
}
public char genConsonant() throws MyException {
char c = generateChar();
if (isVowel(c))
throw new MyException(c + " is not is not a consonant!")
;
return c;
}
public char readChar() {
BufferedReader in = new BufferedReader(new InputStreamReader(Sys
tem.in));
try {
return (char) in.read();
} catch (IOException e) {
}
return ' ';
}

public String readCmd() {


BufferedReader in = new BufferedReader(new InputStreamReader(Sys
tem.in));
try {
return in.readLine();
} catch (IOException ioe) {
System.out.println(ioe.toString());
System.exit(1);
}
return null;
}
}
package myPackagelab6;
public class MainClass {
public static void main(String[] args) {
Generate gen = new Generate();
loop: for (;;) {
System.out.println("Type
System.out.println("Type
System.out.println("Type
System.out.println("Type

1
2
3
4

to
to
to
to

generate
generate
generate
generate

a vowel");
a consonant");
any letter");
an array of chara

cters");
System.out.print("\nType your choice: ");
switch (gen.readChar()) {
case '1':
try {
System.out.println("The vowel you reques
ted is: "
+ gen.genVowel());
} catch (MyException e) {
System.out.println(e);
}
break loop;
case '2':
try {
System.out.println("The consonant you re
quested is: "
+ gen.genConsonant());
} catch (MyException e) {
System.out.println(e);
}
break loop;
case '3':
System.out.println("The character you requested
is: "
+ gen.generateChar());
break loop;
case '4':
System.out.print("Type length of the array: ");
int n = Integer.parseInt(gen.readCmd());
String ar = "";
int cont = 1;
do {
try {

ar += gen.genVowel();
} catch (MyException e) {
ar += "*";
}
for (int j = 1; (j <= cont) && (j < n);
j++) {
try {
ar += gen.genConsonant()
;
} catch (MyException e) {
ar += "*";
}
}
cont++;
n -= cont;
} while (n > 0);
System.out.println(ar);
break loop;
}
}
}
}
//
6. The department for population control needs a program which should ve
rify if a CNP is valid. In the class CNP implement a method which receives as
//parameter a string of characters and verifies if it represents a valid CNP. Th
e method will throw InvalidFormatException if the string has less than 13
//characters or is not numeric, IllegalArgumentException if the string doesn't s
tart with 1 or 2 and NumberFormatException if the characters on the positions
//2 7 don't form a valid date.
//
The main method from the test class, catches the exceptions triggered by
CNP and displays corresponding messages. Read from the keyboard 5 CNPs and veri
fy
//if they are valid.
package myPackagelab6;
@SuppressWarnings("serial")
public class IllegalArgumentException extends Exception {
public IllegalArgumentException(String arg0) {
super(arg0);
}
}
package myPackagelab6;
@SuppressWarnings("serial")
public class InvalidFormatException extends Exception {
public InvalidFormatException(String arg0) {
super(arg0);
}
}
package myPackagelab6;
public class Verify {
public void checkLength(String s) throws InvalidFormatException {

if (s.length() != 13) {
throw new InvalidFormatException("length not ok");
}
try {
long n = Long.parseLong(s);
} catch (NumberFormatException e) {
throw new InvalidFormatException("not numeric");
}
}
public void checkFirst(String s) throws IllegalArgumentException {
int n = Integer.parseInt(s.substring(0, 1));
if ((n < 1) || (n > 2)) {
throw new IllegalArgumentException(
"first character different from 1 or 2")
;
}
}
public void checkDate(String s) throws NumberFormatException {
boolean ok = true;
int x = Integer.parseInt(s.substring(3, 5));
ok = (x < 1) || (x > 12) ? false : ok;
x = Integer.parseInt(s.substring(5, 7));
ok = (x < 1) || (x > 31) ? false : ok;
if (!ok) {
throw new NumberFormatException(s.substring(1, 7)
+ " is not a valid date");
}
}
}
package myPackagelab6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainClass {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(Sys
tem.in));
Verify ver = new Verify();
String[] a = new String[5];
for (int i = 0; i < a.length; i++) {
System.out.print("Type the CNP: ");
try {
a[i] = in.readLine();
} catch (IOException e) {
}
}
for (int i = 0; i < a.length; i++) {
try {
ver.checkLength(a[i]);
ver.checkFirst(a[i]);

ver.checkDate(a[i]);
System.out.println("The CNP:" + a[i] + " is vali
d");
} catch (InvalidFormatException e) {
System.out.print("The CNP:" + a[i] + " is not va
lid ");
System.out.println(e);
} catch (IllegalArgumentException e) {
System.out.print("The CNP:" + a[i] + " is not va
lid ");
System.out.println(e);
} catch (NumberFormatException e) {
System.out.print("The CNP:" + a[i] + " is not va
lid ");
System.out.println(e);
}
}
}
}

You might also like