0% found this document useful (0 votes)
9 views

Chapter 5 Input in Java

Uploaded by

anubhabb93
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Chapter 5 Input in Java

Uploaded by

anubhabb93
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Chapter 5: Input In Java

Name the following

Q1) A package needed to import scanner class


Ans:-java.util

Q2) A method that accepts a character through scanner object


Ans:- In.next().charAt(0)
Or charAt()

Q3) A package needed to import Stream Reader Class


Ans:-java.io

Q4) A method to accept an exponential value through scanner object


Ans:-nextDouble()

Q4) A method to accept an real number through scanner object


Ans:-nextDouble() or nextFloat()

Q5) A method that accepts an integer token through scanner object


Ans:-nextInt()

Write down the syntax with reference to Java Programming

Q1) To accept an integral value 'p' through Stream Class


Ans:-InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int p = Integer.parseInt(in.readLine());

Q2) To accept a fractional value (float) 'm' through Scanner Class


Ans:-Scanner in = new Scanner(System.in);
float m = in.nextFloat();

Q3) To accept a character 'd' through Stream Class


Ans:-InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
char d = (char)in.read();

Q4) To accept a fraction value 'n' in double data type through Stream Class
Ans:-InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
double n = Double.parseDouble(in.readLine());

Q5) To accept a word 'wd' through Stream Class


Ans:-InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
String wd = in.readLine();

Q6) To create a scanner object


Ans:-Scanner in = new Scanner(System.in);
Differentiate between the following

Q1) nextInt( ) and nextFloat( ) methods

nextInt( ) nextFloat( )
Scans the next token of input as an int Scans the next token of input as a float

Q2) Syntax and logical errors

Syntax Errors Logical Errors


Syntax Errors occur when we violate the rules of writing Logical Errors occur due to our mistakes in
the statements of the programming language. programming logic.
Program compiles and executes but doesn't give
Program fails to compile and execute.
the desired output.
Logic errors need to be found and corrected by
Syntax Errors are caught by the compiler.
the people working on the program.

Answer the following

Q1) What do you mean by scanner class?


Ans:-Scanner class is used to get user input at the time of execution of program. It is present in java.util
package.

Q2) What are the different ways to give inputs in a Java Program?
Ans:-Java provides 3 ways to read user input from console:
1. By using BufferedReader class
2. By using Scanner class
3. By using console class

Q3) What is the use of the keyword import?


Ans:-import keyword is used to import built-in and user-defined packages into our Java program.

Q4) What is a package? Give an example.


Ans:-In Java, a package is used to group related classes. Packages are of 2 types:
1. Built-In packages — These are provided by Java API (Application Programming Interface)
2. User-Defined packages — These are created by the programmers to efficiently structure their code.
java.util, java.lang are a couple of examples of built-in packages.

Q5) Give an example to input an integer number by using function argument


Ans:-public class sum
Public static void main(int x)

Q6) Diagnostical messages detect only syntax error. Give comments.


Ans:- Syntax and link errors are detected by one part of the compiler system at the time of compilation.
Specially the compiler component provides diagnostic messages that help programmer locate and identify
syntax errors.
Q6) What is a compound statement? Give an example.
Ans:-Two or more statements can be grouped together by enclosing them between opening and closing curly
braces. Such a group of statements is called a compound statement.

if (a < b)
{
System.out.println("a is less than b");
a = 10;
b = 20;
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);
}

Q7) Write down the syntax to input a character through scanner class with an example.
Syntax:
char <variable name> = <Scanner Object>.next().charAt(0);
Example:
Scanner in = new Scanner(System.in);
char ch = in.next().charAt(0);

Q8) What do you understand by 'Run Time' error? Explain with an example
Ans:-Errors that occur during the execution of the program primarily due to the state of the program which can
only be resolved at runtime are called Run Time errors.
Example:
import java.util.Scanner;
public class RunTimeError
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = in.nextInt();
int result = 100 / n;
System.out.println("Result = " + result);
}
}

This program will work fine for all non-zero values of n entered by the user. When the user enters zero, a run-
time error will occur as the program is trying to perform an illegal mathematical operation of division by 0.
When we are compiling the program, we cannot say if division by 0 error will occur or not. It depends entirely
depends on the state of the program at run-time.

Q9) What are the different types of errors that take place during the execution of a program?
Ans:-Logical errors and Run-Time errors occur during the execution of the program.

Q10) Distinguish between:

Testing Debugging
In the process of Testing, we check if the program is working as
In the process of Debugging, we correct the
expected and find out the errors if it is not giving the expected
errors that were found during testing.
output.
Syntax Error Logical Error
Syntax Errors occur when we violate the rules of writing the Logical Errors occur due to our mistakes in
statements of the programming language. programming logic.
Program compiles and executes but doesn't
Program fails to compile and execute.
give the desired output.
Logical errors need to be found and
Syntax Errors are caught by the compiler. corrected by people working on the
program.
Solutions to Unsolved Java Programs

Q1) The time period of a Simple Pendulum is given by the formula:


T = 2π√(l/g)

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

import java.util.Scanner;
public class Pendulum
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter length: ");
double l = in.nextDouble();
System.out.print("Enter g: ");
double g = in.nextDouble();
double t = 2 * (22.0 / 7.0) * Math.sqrt(l/g);
System.out.println("T = " + t);
}
}
Output:-
l: 0.75
g=9.8
t=1.7388904819706767

Q2) Write a program by using class 'Employee' to accept Basic Pay of an employee. Calculate the
allowances/deductions as given below.

Allowance / Deduction Rate


Dearness Allowance (DA) 30% of Basic Pay
House Rent Allowance (HRA) 15% of Basic Pay
Provident Fund (PF) 12.5% of Basic Pay

Finally, find and print the Gross and Net pay.


Gross Pay = Basic Pay + Dearness Allowance + House Rent Allowance
Net Pay = Gross Pay - Provident Fund

import java.util.Scanner;
public class Employee
{
public void computePay()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Basic Pay: ");
double bp = in.nextDouble();
double da = bp*30/100;
double hra = bp*15/100;
double pf = bp*12.5/100;
double gp = bp + da + hra;
double np = gp - pf;
System.out.println("Gross Pay = " + gp);
System.out.println("Net Pay = " + np);
}
}
Output:-
bp=85000
gp=123250.0
np=112625.0
Q3) 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.

import java.util.Scanner;
public class CameraPrice
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter printed price of Digital Camera:");
double mrp = in.nextDouble();
double disc = mrp * 10 / 100.0;
double price = mrp - disc;
double gst = price * 6 / 100.0;
price = price+ gst;
System.out.println("Amount to be paid: " + price);
}
}

Q4) 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 an article as the input.

import java.util.Scanner;
public class Discounts
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter price of article: ");
double price = in.nextDouble();

double d1 = price * 30 / 100.0;


double amt1 = price - d1;
System.out.println("30% discount = " + d1);
System.out.println("Amount after 30% discount = " + amt1);
double d2 = price * 20 / 100.0;
double amt2 = price - d2;
double d3 = amt2 * 10 / 100.0;
amt2=amt2- d3;
System.out.println("20% discount = " + d2);
System.out.println("10% discount = " + d3);
System.out.println("Amount after successive discounts = " + amt2);
}
}
Q5)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 = 5000, Rate =10%, Time = 3 yrs
Sample Output: Interest for the first year: 500
Interest for the second year: 550
Interest for the third year: 605

import java.util.Scanner;
public class CompoundInterest
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter sum of money: ");
double p = in.nextDouble();
double interest = p * 5 * 1 / 100.0;
System.out.println("Interest for the first year = " + interest);
p=p + interest;
interest = p * 5 * 1 / 100.0;
System.out.println("Interest for the second year = " + interest);
p =p+ interest;
interest = p * 5 * 1 / 100.0;
System.out.println("Interest for the third year = " + interest);
}
}

Q6) A businessman wishes to accumulate 3000 shares of a company. However, he already has some shares of
that company valuing 10 (nominal value) which yield 10% dividend per annum and receive 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.
No. of share = (Annual dividend * 100) / (Nominal value * div%)

Hints:-
Dividend=X*10*10/100=2000
X=2000*100/(10*10)

public class Shares


{
public static void main(String args[])
{
int sharesHeld = (2000 * 100)/(10 * 10);
System.out.println("No. of shares held currently = " + sharesHeld);
int sharesRequired = 3000 - sharesHeld;
System.out.println("No. of shares to purchase = " + sharesRequired);
}
}
Q7) 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

import java.util.Scanner;
public class TimeConvert
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter time in seconds: ");
long secs = in.nextLong();
long hrs = secs / 3600;
secs = secs % 3600;
long mins = secs / 60;
secs = secs % 60;
System.out.println(hrs + " Hours " + mins + " Minutes " + secs + " Seconds");
}
}

Q8) 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

import java.util.Scanner;
public class Swap
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter two unequal numbers");
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a + " b = " + b);
}
}
Q9) A certain amount is invested at the rate 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) / 100
A = P * (1 + (R/100))T
CI = A - P

import java.util.Scanner;
public class InterestDifference
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Amount: ");
double p = in.nextDouble();
double si = p * 10 * 3 / 100;
double ciAmt = p * Math.pow(1 + (10/100.0), 3);
double ci = ciAmt - p;
System.out.print("Difference between CI & SI: " + (ci - si));
}
}

Q10) 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 input.
Hint: CP = (SP / (1 + (profit / 100))) (when profit)
CP = (SP / (1 - (loss / 100))) (when loss)

import java.util.Scanner;
public class Shopkeeper
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the selling price: ");
double sp = in.nextDouble();
double cp1 = (sp / (1 + (20 / 100.0)));
double cp2 = (sp / (1 - (20 / 100.0)));
double totalCP = cp1 + cp2;
System.out.println("Total Cost Price = " + totalCP);
}
}

You might also like