Chapter 5

I. Name the following:

1. a package needed to import Scanner class

2. a method that accepts a character through Scanner object

3. a package needed to import StreamReader class

4. a method to accept an exponential value through Scanner object

5. a method that accepts an integer token through Scanner object

Ans.

1. java.util

2. next( ).charAt( )

3. java.io

4. nextDouble();

5. nextInt( )

II. Write down the syntax with reference to Java programming:

1. to accept an integral value ‘p’ through Stream class

2. to accept a fractional value (float) ‘m’ through Scanner class

3. to accept the character ‘d’ through Stream class

4. to accept a fraction value ‘n’ in double data type through Stream class

5. to accept a word ‘wd’ through Stream class

6. to create a Scanner object.

Ans.

Note: BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

1. int p = Integer.parseInt( br.readLine( ));

2. float m=ob.nextFloat( );

3. char ch = (char) (br.read( ));

4. double n = Double.parseDouble(br.readLine( ));

5. String str = br.readLine( );

6. Scanner ob=new Scanner(System.in);

III. Differentiate between the following:

1. nextInt( ) and nextFloat( )methods

Ans. nextInt( ) receives and returns the token as a int data type whereas nextFloat( ) receives and returns the token as a float data type.

2. Syntax and Logical errors

Syntax error

  • These errors occur when the rules or the grammar of the programming language is not followed.
  • The output is not obtained since the program does not execute due to compiler errors.
  • For example, missing semicolon, undefined variables, misspelt keywords, missing brackets etc

Logical error

  • It is the error in planning the program’s logic. The computer does not know that an error has been made.
  • The system simply follows the instructions and compiles without errors, but the execution does not yield the desired output.
  • For example, to find the product instead of using ‘*’ sign, the programmer might have used ‘+’ sign which yields the incorrect result.

IV Answer the following:

1. What do you mean by Scanner class?

Ans. Scanner class is available in the system package java.util which must be imported. After importing this package and creating a Scanner object, the user can avail various methods provided in the Scanner class to manipulate input data. String manipulation is easier in Scanner class as each word can be obtained as a token and handled separately. 

2. What are the different ways to give inputs in Java programming?

Ans. Input in Java can be obtained by three different methods:

i) By Using Command Line Arguments

Here, the data values are passed through arguments at the time of execution. The values passed through the console are received by a String type args[ ]array (subscript wise) as arguments to the parse function. These values are further converted to the required data type for storage in the corresponding variables.

Example 1

int  a = Integer.parseInt( args[0] );

float b= Float.parseFloat( args[1]);

ii) By Using Input Stream

InputStream requires Buffer ( a temporary storage) for the data values to be stored through an object. However, it requires the importing of java.io package to perform all input output operations.

Example

InputStreamReader ir=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(ir);

[or]

BufferedReader br=new BufferedReader (new InputStreamReader(System.in));

This object br can be used to invoke the various input methods of the BufferedReader class as follows:

String s = br. readLine( );

int n = Integer.parseInt( br.readLine( ));

float f = Float.parseFloat( br.readLine( ));

double d = Double.parseDouble(br.readLine( ));

iii) By Using Scanner class

To accept the input using this method, first import the java.util package and then create the object of the Scanner class. Then invoke any of the methods of the Scanner class through the Scanner object.

Example

Scanner sn=new Scanner (System.in);

double d = sn.nextDouble( );

3. What is the use of the keyword ‘import’?

Ans. The keyword ‘import’ is used to import a package into the current program. When a package is imported, all the classes and methods available in the package can be used in the program.

4. What is a package? Give an example.

Ans.  A package in Java is a collection of logically related classes. For example, all mathematical functions are included in a class called ‘Math’ that is a part of java.lang package which is a default package that is automatically imported into every program.

5. What is the use of the keyword ‘import’ in Java programming?

Ans. The keyword import is used to import a complete package or a particular class of a package into the program.

Example: import java.util.*   [or]   import java.util.Scanner

6. What is a compound statement? Give an example.

Ans.

A compound statement refers to a set of statements enclosed within curly brackets.

Example

if (a>b)

{sum = a+b;

  Pdt = a*b;

}

7. Write down the syntax to input a character through Scanner class with an example.

Ans.

char ch = ob.next( ).charAt(0);

8. What do you understand by ‘Run Time’ error? Explain with an example.

Ans.

Sometimes, the program does not produce the desired results even after the compilation errors are removed. This is due to incorrect mathematical tasks or due to input of incorrect data. Since the compiler does not respond properly while executing a statement, it is called a runtime error. For example, when a number is divided by 0, it results in a runtime error.

9. What are the different types of errors that take place during the execution of a program?

Ans.

Generally, there are three types of errors that occur in a computer program. They are as follows:

  • Syntax errors
  • Logical errors
  • Runtime errors

10. Distinguish between:

a) Testing and Debugging

b) Syntax error and Logical error – repeated – Refer to III main 2nd question

Ans.

a)Testing and Debugging

Testing

i) Testing is a process in which a program is validated.

ii) Testing is complete when all desired verifications against specifications have been performed.

Debugging

i)  Debugging is a process in which the errors in the program are removed.

ii) Debugging is finished when there are no errors and the program executes producing the desired result.

b) Syntax error and Logical error – repeated – Refer to III main 2nd question

V Java Programming

  1. The time period of a Simple Pendulum is given by the formula:

Write a program to calculate the time period of a Simple Pendulum by taking length (l) and acceleration due to gravity(g) as inputs. [

Solution:

class Q1{

void main(double l, double g)  //Input of Length and Acceleration due to gravity

{

double T,pi=22/7.0;

T=2*pi*Math.sqrt(l/g);

System.out.println(“Time Period=”+T);

}}

  • Write a program by using class ‘Employee’ to accept Basic Pay of an employee. Calculate the allowances/deductions as given below. Finally find and print the Gross and Net Pay.

Allowances /Deduction rate

Dearness Allowance (DA)        : 30% of the Basic Pay

House Rent Allowance(HRA) : 15% of the Basic Pay

Provident Fund                        : 12.5% of the Basic Pay

Gross Pay=Basic Pay + Dearness Allowance + House Rent Allowance.

Net Pay=Gross Pay-Provident Fund

Solution:

class Employee{

void main(double basic)

{

double da,hra,pf,gross,net;

da=30/100.0 * basic;

hra=15/100.0 * basic;

pf=12.5/100 * basic;

gross=basic +da+hra;

net=gross-pf;

System.out.println(“Gross Pay=”+gross);

System.out.println(“Net Pay=”+net);

}}

  • A shopkeeper offers 10% discount on the printed price of a Digital Camera. However, a customer has to pay 6% GST on the remaining amount. Write a program in Java to calculate the amount to be paid by the customer taking printed price as an input.

Solution:

class Q3{

void main(double price)

{double dis,gst,amt1,amt2;

dis=10/100.0 * price;

amt1=price-dis;

gst=6/100.0 * amt1;

amt2=amt1+gst;

System.out.println(“The amount after discount and GST=”+amt2);

}}

  • A shopkeeper offers 30% discount on purchasing articles whereas the other shopkeeper offers two successive discounts 20% and 10% for purchasing the same articles. Write a program in Java to compute and display the discounts. Take the price of the article as the input.

Solution:

import java.util.*;

public class Q4{

static void main()

{

Scanner sr=new Scanner(System.in);

double price,xamt,yamt1,yamt2;

System.out.println(“Enter the price of the article”);

price=sr.nextDouble();

xamt=price – 30/100.0 * price;

yamt1=price – 20/100.0 *price;

yamt2= yamt1- 10/100.0* yamt1;

System.out.println(“Price in Shop1=”+xamt);

System.out.println(“Price in Shop2=”+yamt2);

}}

  • Mr.Agarwal invests certain sum at 5% per annum compound interest for three years. Write a program in Java to calculate:

a) the interest for the first year

b) the interest for the second year

c) the amount after three years

Take sum as an input from the user.

Sample Input    : Principal = Rs.5000, Rate = 10% , Time = 3years

Sample Output :

Interest for the first year    = Rs.500

Interest for the second year=Rs.550

Interest for the third year  =Rs.605

Solution:

class Q5

{

void main(double p,double r,double t)

{ double si,amt;

t=1;                          //time is set always as one year since it is a yearly calculation

//YEAR 1

si=p*r*t/100;

System.out.println(“Interest for the first year=”+si);

amt=p+si;

//YEAR 2

p=amt;                   // 1st year’s amt is 2nd year’s principal

si=p*r*t/100;

System.out.println(“Interest for the second year=”+si);

amt=p+si;

//YEAR 3

p=amt;                 // 2nd year’s amt is 3rd year’s principal

si=p*r*t/100;

System.out.println(“Interest for the third year=”+si);

}}

  • A business man wishes to accumulate 3000 shares of a company. However, he already has some shares of that company valuing Rs.10 (nominal value) which yield 10% dividend per annum and receive Rs.2000 as dividend at the end of the year. Write a program in Java to calculate the number of shares he has and how many more shares to be purchased to make his target.

Hint : No. of Share = Annual dividend *100

                                     Nominal value *div%

Solution:

import java.util.*;

class Q6{

static void main()

{Scanner sr=new Scanner(System.in);

double nv,div,ad,s,ns,nns;

nv=10.0;

div=10.0;

ad=2000.0;

s=3000;

ns=(ad*100)/(nv*div);

nns=s-ns;

System.out.println(“The number of shares already possessed=”+(int)ns);

System.out.println(“The number of shares to be purchased=”+(int)nns);

}}

  • Write a program to input the time in seconds. Display the time after converting them into hours, minutes and seconds.

Sample Input    : Time in seconds  5420

Sample Output : 1 Hour 30 Minutes 20 Seconds

Solution:

class Q7{

static void main(long sec)

{

long hr,min,rem;

hr=sec/3600;

rem=(sec%3600);

min=rem/60;

sec=rem%60;

System.out.println(“hour=”+hr);

System.out.println(“minute=”+min);

System.out.println(“seconds=”+sec);

}}

  • Write a program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable.

Sample Input    : a=23, b=56

Sample Output : a=56, b=23

Solution:

import java.util.*;

class Q8_101{

static void main()

{Scanner sr=new Scanner(System.in);

int a,b;

System.out.println(“Enter the values of a and b”);

a=sr.nextInt();

b=sr.nextInt();

a=a+b;

b=a-b;                                                              //This means b=a+b – b. So b gets a’s value

a=a-b;                                                               //This means a=a+b – a. So now a gets b’s value

System.out.println(“The numbers after swapping are shown below”);

System.out.println(“a=” +a);

System.out.println(“b=” +b);

}}

  • A certain amount is invested at the rate of 10% per annum for 3 years. Find the difference between Compound Interest (CI) and Simple Interest (SI). Write a program to take amount as an input.

Hint : SI= P*R*T        A = P*(1+ R/100)T    and CI=A-P

                   100

Solution:

import java.util.*;

class Q9{

static void main()

{

double p,r,t,si,ci,a,y,diff;

Scanner sr=new Scanner(System.in);

System.out.println(“Enter the value of P”);

p=sr.nextDouble();

r=10.0;

t=3.0;

si=p*r*t/100.0;

System.out.println(“Simple Interest=”+si);

y=1+(r/100.0);

a= p * Math.pow(y,t);

ci=a-p;

System.out.println(“Compound Interest=”+ci);

diff=ci-si;

System.out.println(“Difference between compound interest and simple interest=”+diff);

}}

  1. A shopkeeper sells two calculators for the same price. He earns 20% profit on one and suffers a loss of 20% on the other. Write a program to find his total cost price of the calculators by taking selling price as an input.

Hint:

CP =    SP                                        

            (1+profit/100)      (when profit)

CP =    SP                                         

            (1+loss/100)      (when loss)

Solution:

import java.util.*;

class Q10{

static void main()

{

Scanner sr=new Scanner(System.in);

double sp,profit=20,loss=20,cp1,cp2,tot;

System.out.println(“Enter the S.P.”);

sp=sr.nextInt();

cp1=sp/(1+profit/100);

cp2=sp/(1- loss/100);

tot=cp1+cp2;

System.out.println(“The C.P. of the first calculator with 20% profit=”+(float)cp1);

System.out.println(“The C.P. of the second calculator with 20% loss=”+(float)cp2);

System.out.println(“The total cost of both the calculators=”+(float)tot);

}}

****************

%d bloggers like this: