Class 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

Java Basic Input and Output

Java Input

Java provides different ways to get input from the user. However, in this
tutorial, you will learn to get input from user using the object of Scanner class.
In order to use the object of Scanner , we need to
import java.util.Scanner package.

import java.util.Scanner;

To learn more about importing packages in Java, visit Java Import Packages.
Then, we need to create an object of the Scanner class. We can use the object
to take input from the user.

// create an object of Scanner


Scanner input = new Scanner(System.in);

// take input from the user


int number = input.nextInt();

Example: Get Integer Input From the User


import java.util.Scanner;

class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = input.nextInt();
System.out.println("You entered " + number);

// closing the scanner object


input.close();
}
}
Run Code

Output:

Enter an integer: 23
You entered 23

In the above example, we have created an object named input of


the Scanner class. We then call the nextInt() method of the Scanner class to get
an integer input from the user.
Similarly, we can use nextLong() , nextFloat() , nextDouble() , and next() methods
to get long , float , double , and string input respectively from the user.

Java Scanner Class


Java Scanner class allows the user to take input from the console. It belongs
to java.util package. It is used to read the input of primitive types like int, double, long,
short, float, and byte. It is the easiest way to read input in Java program.

Syntax
1. Scanner sc=new Scanner(System.in);

The above statement creates a constructor of the Scanner class having System.inM as
an argument. It means it is going to read from the standard input stream of the
program. The java.util package should be import while using Scanner class.
It also converts the Bytes (from the input stream) into characters using the platform's
default charset.

Methods of Java Scanner Class


Java Scanner class provides the following methods to read different primitives types:

Method Description

int nextInt() It is used to scan the next token of the input as


an integer.

float nextFloat() It is used to scan the next token of the input as a


float.

double nextDouble() It is used to scan the next token of the input as a


double.

byte nextByte() It is used to scan the next token of the input as a


byte.

String nextLine() Advances this scanner past the current line.

boolean nextBoolean() It is used to scan the next token of the input into
a boolean value.

long nextLong() It is used to scan the next token of the input as a


long.

short nextShort() It is used to scan the next token of the input as a


Short.

BigInteger nextBigInteger() It is used to scan the next token of the input as a


BigInteger.
BigDecimal nextBigDecimal() It is used to scan the next token of the input as a
BigDecimal.

Example of integer input from user

The following example allows user to read an integer form the System.in.

1. import java.util.*;
2. class UserInputDemo
3. {
4. public static void main(String[] args)
5. {
6. Scanner sc= new Scanner(System.in); //System.in is a standard input stream
7. System.out.print("Enter first number- ");
8. int a= sc.nextInt();
9. System.out.print("Enter second number- ");
10. int b= sc.nextInt();
11. System.out.print("Enter third number- ");
12. int c= sc.nextInt();
13. int d=a+b+c;
14. System.out.println("Total= " +d);
15. }
16. }

Output:

Example of String Input from user


Let's see another example, in which we have taken string input.

1. import java.util.*;
2. class UserInputDemo1
3. {
4. public static void main(String[] args)
5. {
6. Scanner sc= new Scanner(System.in); //System.in is a standard input stream
7. System.out.print("Enter a string: ");
8. String str= sc.nextLine(); //reads string
9. System.out.print("You have entered: "+str);
10. }
11. }

Output:

Java brings various Streams with its I/O package that helps the user perform all
the Java input-output operations.

These streams support all types of objects, data types, characters, files, etc. to
fully execute the I/O operations. Input in Java can be with certain methods
mentioned below in the article.

Methods to Take Input in Java

There are two ways by which we can take Java input from the user or from a
file
 BufferedReader Class
 Scanner Class

1. Using BufferedReader Class for String Input In Java


It is a simple class that is used to read a sequence of characters. It has a
simple function that reads a character another read which reads, an array of
characters, and a readLine() function which reads a line.
InputStreamReader() is a function that converts the input stream of bytes into a
stream of characters so that it can be read as BufferedReader expects a stream
of characters. BufferedReader can throw checked Exceptions.

Below is the implementation of the above approach:

 Java
// Java Program for taking user
// input using BufferedReader Class
import java.io.*;

class GFG {

// Main Method
public static void main(String[] args)
throws IOException
{
// Creating BufferedReader Object
// InputStreamReader converts bytes to
// stream of character
BufferedReader bfn = new BufferedReader(
new InputStreamReader(System.in));

// String reading internally


String str = bfn.readLine();

// Integer reading internally


int it = Integer.parseInt(bfn.readLine());

// Printing String
System.out.println("Entered String : " + str);

// Printing Integer
System.out.println("Entered Integer : " + it);
}
}

Output
Mayank Solanki
888
Entered String : Mayank Solanki
Entered Integer : 888
Using Buffer Reader Class To Read the Input
Below is the implementation of the above approach:
 Java
/*package whatever //do not write package name here */

import java.io.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Easy {
public static void main(String[] args)
{
// creating the instance of class BufferedReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
String name;
try {
System.out.println("Enter your name");
name = reader.readLine(); // taking string input
System.out.println("Name=" + name);
}
catch (Exception e) {
}
}
}

Output:
Enter your name:
Geeks
Name=Geeks

Example 2:
Java
// Java Program to implement
// Scanner Class to take input
import java.io.*;
import java.util.Scanner;

// Driver Class
class Easy {
// main function
public static void main(String[] args)
{
// creating the instance of class Scanner
Scanner obj = new Scanner(System.in);
String name;
int rollno;
float marks;

System.out.println("Enter your name");


// taking string input
name = obj.nextLine();
System.out.println("Enter your rollno");

// taking integer input


rollno = obj.nextInt();
System.out.println("Enter your marks");

// taking float input


marks = obj.nextFloat();

// printing the output


System.out.println("Name=" + name);
System.out.println("Rollno=" + rollno);
System.out.println("Marks=" + marks);
}
}

Output
Enter your name
Geeks
Enter your rollno
5
Enter your marks
84.60
Name=Geeks
Rollno=5
Marks=84.60

Example :

import java.util.Scanner; // import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}

Output
Enter username
a bc

Username is: abc

Example

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

Differences Between BufferedReader and Scanner


 BufferedReader is a very basic way to read the input generally used to read
the stream of characters. It gives an edge over Scanner as it is faster than
Scanner because Scanner does lots of post-processing for parsing the input;
as seen in nextInt(), nextFloat()
 BufferedReader is more flexible as we can specify the size of stream input to
be read. (In general, it is there that BufferedReader reads larger input than
Scanner)
 These two factors come into play when we are reading larger input. In
general, the Scanner Class serves the input.
 BufferedReader is preferred as it is synchronized. While dealing with multiple
threads it is preferred.
 For decent input, and easy readability. The Scanner is preferred over
BufferedReader.

What do you mean by scanner class?

Scanner class is used to get user input. It is present in java.util package.

What are the different ways to give inputs in a Java Program?

Java provides 4 ways to read user input from console:

a) By using assignment statement


b) By using function argument
c) By using Input Stream Reader class
d) By using Scanner class

3. What is the use of the keyword import?

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

4. What is a package?

Give an example. 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

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.

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

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

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


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. For example: int a = 1, b = 20; if
(a < b) { System.out.println("a is less than b"); } else { System.out.println("b is less than a”);}

7.What is initialization of variables? Explain with a help of an example.

Initialization is the assignment of an initial value for a variable during declaration. For example, int a=5;
is a statement where 5 is stored initially into a memory location represented with the name a.+

8. Distinguish between: (a) Testing and Debugging Testing Debugging Testing is a process in which a
program is validated.

Debugging is a process in which the errors in the program are removed. It is a positive activity that
seeks to demonstrate that the program is correct It is a negative activity in a sense that it is centered
around elimination of known errors or bugs. Testing is complete when all desired verifications against
specification have been performed. Debugging is finished when there are no errors and the program is
ready for execution. (b) Syntax error and Logical error Syntax Error Logical Error Syntax Errors occur
when rules of grammar of the programming language are not followed. Logical Errors occur due to our
mistakes in programming logic. Program fails to compile and execute. Program compiles and executes
but doesn't give the desired output. Syntax Errors are caught by the compiler. Logical errors need to be
found and corrected by people working on the program. (c) nextInt() and nextFloat() nextInt()
nextFloat() The nextInt() method is used to input integers through keyboard in Scanner class. The
nextFloat() method is used to input fractional numbers (float) through keyboard in Scanner class.

9. What are comments?

Name the different types of comments used in Java. A comment is a programmer-readable explanation
or annotation in the source code of a computer program. The different types of comments in Java are: •
Single line comment • Multiline comment 10. What are run-time errors? Give two examples. An error
that occurs during the execution of a program is called run time error. The run-time errors are: •
Dividing an integer by zero. • Accessing an element that is out of bounds of an array.

System.out.println(); or

System.out.print(); or

System.out.printf();

to send output to standard output (screen).

Here,
 System is a class
 out is a public static field: it accepts output data.

Let's take an example to output a line.

class AssignmentOperator {
public static void main(String[] args) {

System.out.println("Java programming is interesting.");


}
}

Output:

Java programming is interesting.

Here, we have used the println() method to display the string.

Difference between println(), print() and printf()

 print() - It prints string inside the quotes.


 println() - It prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.
 printf() - It provides string formatting (similar to printf in C/C++ programming).

Example: print() and println()


class Output {
public static void main(String[] args) {

System.out.println("1. println ");


System.out.println("2. println ");

System.out.print("1. print ");


System.out.print("2. print");
}
}
Run Code
Output:

1. println
2. println
1. print 2. print

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

}}

You might also like