Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Input

Chapter 6 covers input handling in Java, focusing on the Scanner class and its methods for reading different data types. It discusses error types such as syntax, runtime, and logical errors, along with the concept of Java packages and import statements. The chapter also includes various programming exercises demonstrating the use of Scanner for input and calculations.

Uploaded by

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

Java Input

Chapter 6 covers input handling in Java, focusing on the Scanner class and its methods for reading different data types. It discusses error types such as syntax, runtime, and logical errors, along with the concept of Java packages and import statements. The chapter also includes various programming exercises demonstrating the use of Scanner for input and calculations.

Uploaded by

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

CHAPTER 6

Input in Java
Section 3: Assignment Questions

1. Suppose you want to use the class MyClass of the package MyPackage.UtilityLibrary in a program
you are writing. What do you need to do to make the following?
i. class MyClass available to your program
Ans. import java.MyPackage.UtilityLibrary.MyClass;

ii. all the classes of the package available to your program


Ans. import java.MyPackage.UtilityLibrary.*;

2. Explain data input technique in a program using the Scanner class.


Ans. (i) nextInt() is used to input an integer data from the standard input device
(iii) nextLine() or next() is used to input a string data from the standard input device
(iv) hasNext() checks if the Scanner has another token in its input
(v) hasNextLine() checks if the Scanner has another line in its input

3. What are delimiters? Which is the default delimiter used in the Scanner class?
Ans. A delimiter is a sequence of one or more characters that separates two tokens. The default
delimiter used in the Scanner class is a white space.

4. What are errors in a program?


Ans. Errors are mistakes in a program that prevent it from its normal working. In programming terms,
errors are often referred to as bugs.

5. Explain the following terms, giving an example of each.


i. Syntax error
Ans. A syntax error occurs due to the fact that the syntax of a programming language is not followed
correctly. For eg. ‘Missing semicolon after a statement’.

ii. Runtime error


Ans. A runtime error occurs during the execution of a program. For eg. ‘Divide by zero error’

iii. Logical error


www.bhuvantechs.com

Ans. A logical error occurs when the program compiles and runs without errors, but produces an
incorrect result. For eg. ‘using wrong variable name’

6. If a student forgot to put a closing quotation mark on a string, what kind error would occur?
Ans. syntax error

7. A program has compiled successfully without any errors. Does this mean the program is error free?
Explain.
Ans. No. The program may have logical error and may give incorrect result.
8. A program needed to read an integer, but the user entered a string instead, and an error occurred
when the program was executed. What kind of error is this?
Ans. Runtime error

9. A student was asked to write a program for computing the area of a rectangle and he, mistakenly,
wrote the program to compute the perimeter of a rectangle. What kind of error is this?
Ans. Logical error

10. What is a java package? Give an example.


Ans. A java package is a named collection of java classes that are grouped on the basis of their
functionality. For eg. Java.util.*;

11. Explain the use of import statement with an example.


Ans. The import statement is used to include a package or class in a program. Eg. Import java.util.*;

12. Distinguish between the following:


i. next() and nextLine()
Ans. next() is used to read the next complete token from the scanner object.
nextLine() is used to read a complete line of text.

ii. next() and next().charAt(0)


Ans. next() is used to read the next complete token from the scanner object.
next().charAt(0) is used to read the next complete token and then the first character is returned using
the charAt(0) method.

iii. next() and hasNext()


Ans. next() is used to read the next complete token from the scanner object.
hasNext() returns true if this scanner has another token in its input.

iv. hasNext() and hasNextLine()


Ans. hasNext() returns true if this scanner has another token in its input.
hasNextLine() returns true if this scanner has another line in its input.

13. Consider the following input:


one, two three, four, five
What values will the following code assign to the variables input1 and input2?
String input1 = keyboard.next();
String input2 = keyboard.next();
Ans. input1 will be assigned one
www.bhuvantechs.com

input2 will be assigned two three one

14. Write a line of code that:


i. Creates a Scanner object named scanner to be used for taking keyboard input.
Ans. Scanner scanner = new Scanner(System.in);

ii. Uses the object scanner to read a word from the keyboard and store it in the String variable named
stg.
Ans. String stg = scanner.next();

Input in Java ~2~


15. Write a code that creates a Scanner object and sets its delimiter to the dollar sign.
Ans.
import java.util.*;
public class PalindromicPrime
{
public static void main(String[] args) {
Scanner scan = new Scanner("Anna Mills$Female$18");
scan.useDelimiter("$");
while(scan.hasNext())
{
System.out.println(scan.next());
}
System.out.println("\nDelimiter being used in Scanner: "+ scan.delimiter());
scan.close();
}
}

16. Write a statement to let the user enter an integer or a double value from the keyboard.
Ans. int input1 = keyboard.nextInt();
double input2 = keyboard.nextDouble();

17. Write a program in Java that takes input using the Scanner class to calculate the Simple Interest
and the Compound Interest with the given values:
i. Principle Amount = Rs.1,00,000
ii. Rate = 11.5%
iii. Time = 5 years
Display the following output:
i. Simple interest
ii. Compound interest
iii. Absolute value of the difference between the simple and compound interest.
Ans.
import java.util .*;
class sici
{
public static void main (String argu[ ])
{
double pr=100000,t=5, sim,com,rate=11.5;
Scanner sc=new Scanner (System. in);
www.bhuvantechs.com

sim=(pr * t * rate)/100;
com=pr * Math.pow(1.0+rate/100.0,t) - pr;
System.out.println("Simple Interest="+sim);
System.out. println("Compound Interest="+com);
System.out. println("Absolute value of the difference between the SI and CI"+(com-sim));
}
}

Input in Java ~3~


18. Write a program to compute the Time Period (T) of a Simple Pendulum as per the following
formula: T =2 π√L/√g
Input the value of L (Length of Pendulum) and g (gravity) using the Scanner class.
Ans.
import java.util.*;
class Simple
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
double Time,pie=22/7,length,g;
System.out.println("Enter the length of pendulum");
length=sc.nextDouble();
System.out.println("Enter the gravity");
g=sc.nextDouble();
Time=2*pie*(Math.sqrt(length)/Math.sqrt(g));
System.out.println("Time taken by simple pendulum is "+Time);
}
}

19. Write a program that takes the distance of the commute in kilometres, the car fuel consumption
rate in kilometre per gallon, and the price of a gallon of petrol as input. The program should then
display the cost of the commute.
Ans.
import java.util.*;
class Simple
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
double dis,price,rate,cost;
System.out.println("Enter the distance to travel in kilometer");
dis=sc.nextDouble();
System.out.println("Enter the car fuel consumption rate in kilometre per gallon");
rate=sc.nextDouble();
System.out.println("Enter the price of a gallon of petrol");
price=sc.nextDouble();
cost=(dis*price)/rate;
www.bhuvantechs.com

System.out.println("Total cost to travel is "+cost);


}
}

20. Write a program in Java that accepts the seconds as input and converts them into the
corresponding number of hours, minutes and seconds. A sample output is shown below:
Enter Total Seconds:
5000
1 Hour(s) 23 Minute(s) 20 Second(s)

Input in Java ~4~


Ans. import java.util.Scanner;
public class seconds
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Total seconds: ");
int seconds = in.nextInt();
int p1 = seconds % 60;
int p2 = seconds / 60;
int p3 = p2 % 60;
p2 = p2 / 60;
System.out.print( p2 + " Hour(s) " + p3 + " Minute(s) " + p1 + " Second(s)");
System.out.print("\n");
}
}

21. Write a program in Java, using the Scanner methods, to read and display the following details:
Name - as a String data type,
Roll Number - as an integer data type,
Marks in 5 subjects - as a float data type,
Compute and display the percentage of marks.
Ans. import java.util.Scanner;
public class seconds
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = in.next();
System.out.print("Enter Roll No.: ");
int roll_no = in.nextInt();
System.out.print("Enter Science Marks: ");
float sci = in.nextFloat();
System.out.print("Enter Maths Marks: ");
float math = in.nextFloat();
System.out.print("Enter English Marks: ");
float eng = in.nextFloat();
System.out.print("Enter Hindi Marks: ");
www.bhuvantechs.com

float hindi = in.nextFloat();


System.out.print("Enter SST Marks: ");
float sst = in.nextFloat();
float per=(sci+math+eng+hindi+sst)/5;
System.out.print( "Percentage scored = "+per);
System.out.print("\n");
}
}

Input in Java ~5~


22. Write a Java program that reads a line of text separated by any number of whitespaces and
outputs the line with correct spacing, that is, the output has no space before the first word and
exactly one space between each pair of adjacent words.
Ans.
import java.util.*;
class Simple
{
public static void main(String args[])
{
String blogName = "Ram has done well in exams";
String nameWithProperSpacing = blogName.replaceAll("\\s+", " ");
System.out.println( nameWithProperSpacing );
}
}

www.bhuvantechs.com

Input in Java ~6~

You might also like