Class 4
Class 4
Class 4
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.
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Output:
Enter an integer: 23
You entered 23
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.
Method Description
boolean nextBoolean() It is used to scan the next token of the input into
a boolean value.
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:
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.
There are two ways by which we can take Java input from the user or from a
file
BufferedReader Class
Scanner Class
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));
// 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;
Output
Enter your name
Geeks
Enter your rollno
5
Enter your marks
84.60
Name=Geeks
Rollno=5
Marks=84.60
Example :
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
Output
Enter username
a bc
Example
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
import keyword is used to import built-in and user-defined packages into our java program.
4. What is a package?
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.
import keyword is used to import built-in and user-defined packages into our Java program.
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.
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();
Here,
System is a class
out is a public static field: it accepts output data.
class AssignmentOperator {
public static void main(String[] args) {
Output:
1. println
2. println
1. print 2. print
Ans.
1. java.util
2. next( ).charAt( )
3. java.io
4. nextDouble();
5. nextInt( )
II. Write down the syntax with reference to Java programming:
Ans.
2. float m=ob.nextFloat( );
Ans. nextInt( ) receives and returns the token as a int data type
whereas nextFloat( ) receives and returns the token as a float data
type.
Syntax error
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:
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
Example
[or]
This object br can be used to invoke the various input methods of the
BufferedReader class as follows:
Example
double d = sn.nextDouble( );
Ans.
Example
if (a>b)
{sum = a+b;
Pdt = a*b;
Ans.
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.
Syntax errors
Logical errors
Runtime errors
Ans.
Debugging
ii) Debugging is finished when there are no errors and the program
executes producing the desired result.
V Java Programming
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);
}}
class Employee{
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);
}}
Solution:
class Q3{
{double dis,gst,amt1,amt2;
dis=10/100.0 * price;
amt1=price-dis;
gst=6/100.0 * amt1;
amt2=amt1+gst;
}}
Solution:
import java.util.*;
double price,xamt,yamt1,yamt2;
price=sr.nextDouble();
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:
Sample Output :
Solution:
class Q5
//YEAR 1
si=p*r*t/100;
amt=p+si;
//YEAR 2
si=p*r*t/100;
amt=p+si;
//YEAR 3
si=p*r*t/100;
System.out.println(“Interest for the third year=”+si);
}}
Solution:
import java.util.*;
class Q6{
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;
}}
Solution:
class Q7{
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);
}}
Solution:
import java.util.*;
class Q8_101{
int a,b;
a=sr.nextInt();
b=sr.nextInt();
a=a+b;
System.out.println(“a=” +a);
System.out.println(“b=” +b);
}}
100
Solution:
import java.util.*;
class Q9{
double p,r,t,si,ci,a,y,diff;
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;
}}
Hint:
CP = SP
(1+profit/100) (when profit)
CP = SP
Solution:
import java.util.*;
class Q10{
double sp,profit=20,loss=20,cp1,cp2,tot;
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);
}}