Thursday, August 16, 2007

Java Programs @ Lab session (2007)

Program, an example on how to accept user I/P......using DataInputStream

import java.io.DataInputStream
class x2
{
public static void main(String s[])
{
float price=0.0f;
float nprice=0.0f;
try
{
DataInputStream in =DataInputStream(System.in);
System.out.println("Number: ");
price=Float.valueOf(in.readline()).floatValue();
}
catch(exception e)
{
newprice=(price*100);
System.out.println(nprice);
}
}
}

Code related to the concept of Branching and Array

CODE-1

class x5
{
public static void main(String[] s)
{
int m[]={30,67,56,39,89,54,90,95,76,98};
int c1=0,c2=0,c3=0,c4=0;
for(int x=0;x<=9;x++)
{
if(m[x]>=0 && m[x]<=40)
{ c1++; }
else
{
if(m[x]>=41 && m[x]<=60)
{ c2++; }
else
{
if(m[x]>=61 && m[x]<=80)
{ c3++; }
else { c4++; }
}
}
}
System.out.println("No. of students scoring marks b/w 0-40: "+c1);
System.out.println("No. of students scoring marks b/w 41-60: "+c2);
System.out.println("No. of students scoring marks b/w 61-80: "+c3);
System.out.println("No. of students scoring marks b/w 81-100: "+c4);
}
}

CODE-2

class x6
{
public static void main(String s[])
{
int c=50,p=67,m=100;
int tl=c+p+m;
if(tl>=200)
{
if(m>=60 &&amp;amp; p>=50 && c>=40)
{
System.out.println("Admission granted");
System.out.println("Total="+tl);
System.out.println("Maths="+m);
System.out.println("Physics="+p);
System.out.println("Chemistry="+c);
}
else
{
System.out.println("Marks obtained insufficient");
}
}
else
{
System.out.println("Admission denied");
}
}
}

Exception Handling, as well as Command Line Argument passing

class x7
{
public static void main(String[] s)
{
try
{
int x=0,y=0;
int a=0,b=0,c=0,d=0,m=0,n=0;
a=Integer.parseInt(s[0]);
b=Integer.parseInt(s[1]);
c=Integer.parseInt(s[2]);
d=Integer.parseInt(s[3]);
m=Integer.parseInt(s[4]);
n=Integer.parseInt(s[5]);
System.out.println("val: "+a+b+c+d+m);
x=((m*d)-(b*n)/(a*d)-(c*b));
y=((n*a)-(m*c)/(a*d)-(c*b));
System.out.println("O/P: x: "+x);
}
catch(Exception e)
{
if(((a*d)-(c*b))==0)
{
System.out.println("Divisor cannot be ZERO/0");
}
}
}
}

No comments: