COMPUTER
PROGRAMMING II WEEK 9
Homework
of the week: run each program and get the results in Word format as homework
Note : One
of these programs will be your next quiz and also be in your final exam.
Exception-
Error control
EX1)
import javax.swing.*; public class H9E1 { public static void main(String arg[]) { double x1,x2; try{ x1=Double.parseDouble(JOptionPane.showInputDialog("x1=")); } catch(NumberFormatException e) {System.out.println("Number format exception,
x1");x1=1.0;} try{ x2=Double.parseDouble(JOptionPane.showInputDialog("x2=")); } catch(NumberFormatException e) {System.out.println("Number format exception,
x2");x2=1.0;} double x3=x1/x2; JOptionPane.showMessageDialog(null,"x3="+x3); } } |
EX2
)
import
javax.swing.*; public
class H9E2 { public
static double divide(int s1,int s2) throws dividebyzeroException { if(s2==0)
throw new dividebyzeroException(); return
(double) s1/s2; } public
static void main(String arg[]) { int
x1,x2; try{ x1=Integer.parseInt(JOptionPane.showInputDialog("x1=")); }
catch(NumberFormatException e) {System.out.println("Number
format exception, x1");x1=1;} try{ x2=Integer.parseInt(JOptionPane.showInputDialog("x2=")); }
catch(NumberFormatException e) {System.out.println("Number
format exception, x2");x2=1;} double
x3=0; try{ x3=divide(x1,x2); }
catch(dividebyzeroException e1) {System.out.println(e1.toString());}
JOptionPane.showMessageDialog(null,"x3="+x3); } } |
public
class dividebyzeroException extends ArithmeticException { private static final long serialVersionUID
= 985786L; public dividebyzeroException() { super("number divided by zero
"); } } |
EX3
)
import
javax.swing.JOptionPane; class
H9E3 { public static void main(String args[]) { double volume; try{ box firstbox= new box(1.0,1.2,0.2); String s="First box : \n"+firstbox.toString()+"\n"; firstbox.write_length(3.0); firstbox.write_width(2.0); firstbox.write_height(-1.0); s+="value changed first box :
\n"+firstbox.toString()+"\n"; JOptionPane.showMessageDialog(null,s, "class example:boxtest4",JOptionPane.PLAIN_MESSAGE); } catch(zero_or_negative_sizeException e1) { JOptionPane.showMessageDialog(null,e1.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);} System.exit(0); } } |
public
class zero_or_negative_sizeException extends ArithmeticException { private static final long serialVersionUID
= 9875958L; public
zero_or_negative_sizeException() {
super("the given dimension is zero or negative "); } } |
class
box { private
double length; private
double width; private
double height; box(double
l,double w, double h) throws zero_or_negative_sizeException { if(l<=0 || w<=0 ||
h<=0) throw new zero_or_negative_sizeException(); else { length=l; width=w; height=h; } } box(box
bi) throws zero_or_negative_sizeException {if(bi.length<=0 || bi.width<=0 || bi.height<=0)
throw new zero_or_negative_sizeException(); else { length=bi.length; width=bi.width; height=bi.height; } } //
This methods are written to access private length, //
width and height variables public
double read_length() {return length;} public
double read_width() {return width;} public
double read_height() {return height;} //This
methods are written to change private length, //
width and height variables public
void write_length(double l) throws zero_or_negative_sizeException {if(l<=0 ) throw new
zero_or_negative_sizeException(); length=l; } public
void write_width(double w) throws zero_or_negative_sizeException {if(w<=0 ) throw new
zero_or_negative_sizeException(); width=w; } public
void write_height(double h) throws zero_or_negative_sizeException {if(h<=0 ) throw new
zero_or_negative_sizeException(); height=h; } double
volume() {return
length*width*height;} public
String toString() { String s=""; s+="length =
"+length+"\n"; s+="width =
"+width+"\n"; s+="height =
"+height+"\n"; s+="Volume =
"+volume()+"\n"; return s; } } |
EX4
) Class
company is given as :
public class company { public String
name; public double capital,balance,profit; public int process; //this method establish the company //constructor method public company(String is,double
Ri) {name=is; capital=Ri; balance=Ri; profit=0; process=0; } public void buy(double x) {balance-=x; process++; if(balance<=0) {System.out.println("company
is broken "+process);} } public void sell(double x) {balance+=x; profit=balance-capital; process++; } public String acount() throws companyisbrokenException { String
s="------------"+name+"--------------------\n"; if(balance<=0) throw new
companyisbrokenException(); //s+="company is broken \n"; else s+="
capital = "+capital+" TL\n"; s+="
balance = "+balance+" TL\n"; s+="
profit = "+profit+" TL\n"; s+="
number of processes = "+process+" \n"; return s; } } |
A class companyisbrokenException is defined as :
public
class companyisbrokenException extends Exception { private static final long serialVersionUID
= 4783855L; public
companyisbrokenException() {
super("the company is broken"); } } |
import javax.swing.*; public
class H9E4 { public static void main(String args[]) { company T=new company("Defne
Holding",1.0e6); for(int i=0;i<100;i++)
{T.buy(100);T.sell(400);} String s=""; String s1="",s2=""; company A=new company("Ali
Limited",100.0); for(int i=0;i<100;i++)
{A.buy(100);A.sell(110);} try{ s1=T.acount(); s+=s1; s2=A.acount(); s+=s2; }catch(companyisbrokenException e) {System.out.println(e.toString());} JOptionPane.showMessageDialog(null,s,
"company class test",JOptionPane.PLAIN_MESSAGE); } } |
Generic
classes
EX5)
arrayprint
public
class arrayprint { public
static void printArray(Integer[] x) {for(int
i=0;i<x.length;i++) System.out.print("
"+x[i]); System.out.println();
} public
static void printArray(Double[] x) {for(int
i=0;i<x.length;i++) System.out.print("
"+x[i]); System.out.println();
} public
static void printArray(Character[] x) {for(int
i=0;i<x.length;i++) System.out.print("
"+x[i]); System.out.println();
} public
static void printArray(String[] x) {for(int
i=0;i<x.length;i++) System.out.print("
"+x[i]); System.out.println();
} public
static void main(String arg[]) { Integer[]
i={1,2,3,4,5,6}; Double[]
d={1.1,2.2,3.3,4.4,5.5,6.6}; Character[]
c={'a','b','c','d','f','g'}; String[]
s={"ali","veli","49","elli"}; printArray(i); printArray(d); printArray(c); printArray(s); } } |
public
class arrayprint1 { public
static<E> void printArray( E[] x) {
for(int
i=0;i<x.length;i++) System.out.print("
"+x[i]); System.out.println();
} public
static void main(String arg[]) { Integer[]
i={1,2,3,4,5,6}; Double[]
d={1.1,2.2,3.3,4.4,5.5,6.6}; Character[]
c={'a','b','c','d','f','g'}; String[]
s={"ali","veli","49","elli"}; printArray(i); printArray(d); printArray(c); printArray(s); } } |
public
class arrayprint2 { public
static void printArray( Object[] x) {for(int
i=0;i<x.length;i++) System.out.print("
"+x[i]); System.out.println();
} public
static void main(String arg[]) { Integer[]
i={1,2,3,4,5,6}; Double[]
d={1.1,2.2,3.3,4.4,5.5,6.6}; Character[]
c={'a','b','c','d','f','g'}; String[]
s={"ali","veli","49","elli"}; printArray(i); printArray(d); printArray(c); printArray(s); } } |
import
javax.swing.*; public
class arrayprint4 { public
static<E> String toString( E[] x) {
String
s=""; for(int i=0;i<x.length;i++) s+="
"+x[i]; return s; } public
static void main(String arg[]) { Integer[]
i={1,2,3,4,5,6}; Double[]
d={1.1,2.2,3.3,4.4,5.5,6.6}; Character[]
c={'a','b','c','d','f','g'}; String[]
s={"ali","veli","49","elli"}; String
s1=toString(i)+"\n"; s1+=toString(d)+"\n"; s1+=toString(c)+"\n"; s1+=toString(s)+"\n"; JOptionPane.showMessageDialog(null,s1); } } |
import
javax.swing.*; public
class arrayprint3 { public
static String toString( Object[] x) { String s=""; for(int i=0;i<x.length;i++) s+="
"+x[i]; return s; } public
static void main(String arg[]) { Integer[]
i={1,2,3,4,5,6}; Double[]
d={1.1,2.2,3.3,4.4,5.5,6.6}; Character[]
c={'a','b','c','d','f','g'}; String[]
s={"ali","veli","49","elli"}; String
s1=toString(i)+"\n"; s1+=toString(d)+"\n"; s1+=toString(c)+"\n"; s1+=toString(s)+"\n"; JOptionPane.showMessageDialog(null,s1); } } |
EX6)
matrix
public
class matrix<E> { public
E[][] A; //constructor
methods public
matrix(E[][] Ai) { try{ @SuppressWarnings("unchecked") final E[][] A1 =(E[][]) new Object[Ai.length][Ai[0].length]; A=A1; }catch(EmptyMatrixException e){}
catch(FullMatrixException f){};
input_matrix(Ai); } public
matrix(matrix<E> M) { try{ @SuppressWarnings("unchecked") final
E[][] A1=(E[][])new Object[M.A.length][M.A[0].length]; A=A1; }catch(EmptyMatrixException e){}
catch(FullMatrixException f){}; input_matrix(M.A); } public matrix(int
n,int m) { try{ @SuppressWarnings("unchecked") final E[][]
A1=(E[][])new Object[n][m]; A=A1;
}catch(EmptyMatrixException
e){}
catch(FullMatrixException f){}; } public void
input_matrix(E[][] Ai) { for(int i=0;i<A.length;i++) { for(int j=0;j<A[0].length;j++) {A[i][j]=Ai[i][j];} } } public
String toString(matrix<E> M) { int n=M.A.length; int
m=M.A[0].length; String
s=""; for(int
i=0;i<n;i++) { for(int
j=0;j<m;j++) {s+=M.A[i][j]+" ";} s+="\n"; } return s; } public
String toString() { int
n=A.length; int
m=A[0].length; String
s1=""; for(int
i=0;i<n;i++) { for(int
j=0;j<m;j++) { s1+=String.format(" %s ",A[i][j]);}
s1+="\n"; } return s1; } //end of method toString
}//end of class matrix |
public
class EmptyMatrixException extends
RuntimeException {private static final long
serialVersionUID = 2097498L; public
EmptyMatrixException() {super("Matrix is empty");} public
EmptyMatrixException(String exception) {super(exception);} } |
public
class FullMatrixException extends
RuntimeException {private static final long
serialVersionUID = 547638L; public
FullMatrixException() {super("Matrix is full");} public
FullMatrixException(String exception) {super(exception);} } |
public
class H9E6 {public static void main(String
arg[]) {Double[][]
a={{1.1,2.2},{3.3,4.4}}; Integer[][] b={{1,2},{3,4}}; Character[][] c={{'a','b'},{'c','d'}}; matrix<Double> A=new
matrix<Double>(a); matrix<Integer> B=new
matrix<Integer>(b); matrix<Character> C=new
matrix<Character>(c); System.out.println(A.toString()); System.out.println(B.toString()); System.out.println(C.toString()); }} |
Using lambda expression
with generic classes
Table
14.3
Important functional
interfaces in Java
Interface name |
Argument |
Returns |
Predicate<T> |
T |
boolean |
Consumer<T> |
T |
void |
Function<T,R> |
T |
R |
BiFunction<T,W,R> |
(T,W) |
R |
Supplier<T> |
None |
T |
UnaryOperator<T> |
T |
T |
BinaryOperator<T>
|
(T,T) |
T |
Binary
Function<T,W,R> |
(T,W) |
R |
Ex7) using generic Function interface
import
java.util.function.*; public class H9E7 { public static void main(String[] arg) {
Function<Double,Double> y = x -> {return x*Math.sin(x);}; System.out.println(y.apply(2.0)); } } |
import
java.util.function.*; public
class H9E7A { public static void
main(String[] arg) { Function<Double,Boolean>
y = x -> (x*x-2.0*x+5)>2; System.out.println(y.apply(2.0)); } } |
Ex8) using generic BiFunction interface
import
java.util.function.*; public class H9E8 { public static void main(String[] arg) {
BiFunction<Double,Double,Double> z = (x,y) -> x*x+y*y;
System.out.println(z.apply(2.0,3.0)); } } |
import
java.util.function.*; public class H9E8A { public static void main(String[] arg) {
BiFunction<Double,Double,Boolean> z = (x,y) -> x*x+y*y>2;
System.out.println(z.apply(2.0,3.0)); } } |
StringTokenizer
class
Ex9)
import java.io.*; import java.util.*; public
class H9E9 { public static void main(String arg[]) { String s="Once upon a time in a
country far far away"; System.out.println("sentence
: "+s); StringTokenizer t=new StringTokenizer(s); System.out.println("word
count : "+t.countTokens()); int i=0; while(t.hasMoreTokens()) {System.out.println("word
index : "+(i++)+" word : "+t.nextToken());} } } |
import javax.swing.*; public
class H9E10 { public static double[]
enterdoublearray(String s) { String s1=JOptionPane.showInputDialog(s); StringTokenizer token=new
StringTokenizer(s1); int n=token.countTokens()-1; int m=n+1; double a[]=new double[m]; int j=0; while(token.hasMoreTokens()) { Double ax=new Double(token.nextToken()); a[j++]=ax.doubleValue(); } return a; } public static String print(double a[]) { String s=""; int n=a.length; int i=0; while(i<n)
{s+=a[i]+"\n";i++;} return s; } public static void main(String arg[]) { double x[]=enterdoublearray("enter a
double array with a space between each number"); JOptionPane.showMessageDialog(null,print(x),"String
Tokenizer Test",JOptionPane.PLAIN_MESSAGE); } } |
ArrayList
class
import
java.util.*; import
javax.swing.*; public
class ArrayList1 {
//print is a generic class public static<E> String
print(Collection<E> c) { String s=""; Iterator<E> i=c.iterator(); while(i.hasNext())
{s+=i.next()+"\n";} return s; } public static void main(String args[]) { ArrayList<Integer> a=new
ArrayList<Integer>(); for(int i=0;i<10;i++) {int sayi=((int)(Math.random()*100)); a.add(new
Integer(sayi)); } String s1="Array List class"; String s=print(a); s+="sorted
list\n"; Collections.sort(a); s+=print(a); s+="reverse
list\n"; Collections.reverse(a); s+=print(a); s+="mixed
list\n"; Collections.shuffle(a); s+=print(a); System.out.println(s); } } |
import
java.util.*; import
javax.swing.*; public
class ArrayList2 { public static void main(String args[]) { ArrayList<Integer> a=new
ArrayList<Integer>(); for(int i=0;i<5;i++) {int sayi=((int)(Math.random()*100)); a.add(new Integer(sayi)); } String s1="Array List class"; String s=""; for (int i=0, n=a.size(); i < n; i++)
{s+=a.get(i)+"\n";}; JOptionPane.showMessageDialog(null,s,s1, JOptionPane.PLAIN_MESSAGE); } } |