In: Computer Science
Objective:
Create a program that uses the methods in the String and Math classes to do the following:
import java.io.*;
class Program
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1, str2;
char ch;
int l1, l2, letters, i, flag1=0, flag2=0, a, b, c;
double d, r1, r2;
System.out.println("Enter first noun");
str1=br.readLine();
System.out.println("Enter second noun");
str2=br.readLine();
l1=str1.length();// length of first noun
l2=str2.length();// length of second noun
letters=str1.compareToIgnoreCase(str2);// comparing the two nouns lexicographically
System.out.println("The diference between the position of two nouns in dictionary is "+letters);
System.out.println("Last letter of "+str1+" is "+str1.charAt(l1-1));// printing last letter of first noun
System.out.println("Last letter of "+str2+" is "+str2.charAt(l2-1));// printing last letter of second noun
for(i=0; i<l1; i++)
{
ch=str1.charAt(i);
if(ch=='e'||ch=='E')
{
System.out.println("The position of letter "+ "e" +" in "+str1+" is "+(i+1));//printing position of "e" in first noun
flag1=1;
break;
}
}
for(i=0; i<l2; i++)
{
ch=str2.charAt(i);
if(ch=='e'||ch=='E')
{
System.out.println("The position of letter "+"e"+" in"+str2+" is "+(i+1));//printing position of "e" in second noun
flag2=1;
break;
}
}
if(flag1==0)
System.out.println("The position of letter "+"e"+" in "+str1+" is -1");
if(flag2==0)
System.out.println("The position of letter "+"e"+" in "+str2+" is -1");
System.out.println("Enter three integer for values of a, b and c in a quadratic equation");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=Integer.parseInt(br.readLine());
d=(b*b)-4*a*c;// calculating discriminant
System.out.println("Roots of the quadratic equation ("+a+")x^2+("+b+")x+("+c+") are:");
if(d<0) //if discriminant less than zero roots don't exist
System.out.println("NAN(Not a number");
else
{ //if discriminat greater than zero roots exist
r1=((-b)+Math.sqrt(d))/(2*1); // using Math.sqrt function
r2=((-b)-Math.sqrt(d))/(2*1); // using Math.sqrt function
System.out.println(r1+" and "+r2);
}
}
}