[Go to site: main page, start]

0% found this document useful (0 votes)
15 views6 pages

Java Input Techniques and Error Handling

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Java Input Techniques and Error Handling

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 6

Input in Java
Section 3: Assignment Questions

1. Suppose you want to use the class MyClass of the package [Link] 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 [Link];

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


Ans. import [Link].*;

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


[Link]

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. [Link].*;

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 [Link].*;

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 = [Link]();
String input2 = [Link]();
Ans. input1 will be assigned one
[Link]

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([Link]);

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

Input in Java ~2~


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

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

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 [Link] .*;
class sici
{
public static void main (String argu[ ])
{
double pr=100000,t=5, sim,com,rate=11.5;
Scanner sc=new Scanner (System. in);
[Link]

sim=(pr * t * rate)/100;
com=pr * [Link](1.0+rate/100.0,t) - pr;
[Link]("Simple Interest="+sim);
[Link]. println("Compound Interest="+com);
[Link]. 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 [Link].*;
class Simple
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
double Time,pie=22/7,length,g;
[Link]("Enter the length of pendulum");
length=[Link]();
[Link]("Enter the gravity");
g=[Link]();
Time=2*pie*([Link](length)/[Link](g));
[Link]("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 [Link].*;
class Simple
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
double dis,price,rate,cost;
[Link]("Enter the distance to travel in kilometer");
dis=[Link]();
[Link]("Enter the car fuel consumption rate in kilometre per gallon");
rate=[Link]();
[Link]("Enter the price of a gallon of petrol");
price=[Link]();
cost=(dis*price)/rate;
[Link]

[Link]("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 [Link];
public class seconds
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter Total seconds: ");
int seconds = [Link]();
int p1 = seconds % 60;
int p2 = seconds / 60;
int p3 = p2 % 60;
p2 = p2 / 60;
[Link]( p2 + " Hour(s) " + p3 + " Minute(s) " + p1 + " Second(s)");
[Link]("\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 [Link];
public class seconds
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Roll No.: ");
int roll_no = [Link]();
[Link]("Enter Science Marks: ");
float sci = [Link]();
[Link]("Enter Maths Marks: ");
float math = [Link]();
[Link]("Enter English Marks: ");
float eng = [Link]();
[Link]("Enter Hindi Marks: ");
[Link]

float hindi = [Link]();


[Link]("Enter SST Marks: ");
float sst = [Link]();
float per=(sci+math+eng+hindi+sst)/5;
[Link]( "Percentage scored = "+per);
[Link]("\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 [Link].*;
class Simple
{
public static void main(String args[])
{
String blogName = "Ram has done well in exams";
String nameWithProperSpacing = [Link]("\\s+", " ");
[Link]( nameWithProperSpacing );
}
}

[Link]

Input in Java ~6~

Common questions

Powered by AI

The Scanner class in Java provides a mechanism for input handling by offering methods that parse primitive types and strings. For example, nextInt() is used to input an integer, nextLine() is used for a line of text, and next() is used for a single string token . The Scanner also supports delimiter management, where the default is whitespace but can be changed using useDelimiter(), thus allowing complex input parsing by recognizing various token separators . These features make Scanner versatile for reading different data types from various input sources.

Delimiters in Java Scanner class play a crucial role in text parsing by defining boundaries between input tokens. The default delimiter is whitespace, enabling separation of words and numbers . Changing the delimiter with methods like useDelimiter() allows customization of tokenization, enabling parsing of complex input formats, such as CSV files or fixed-format records . For instance, setting a dollar sign ('$') as a delimiter can correctly parse currency-related strings, demonstrating how delimiter flexibility allows adaptation to various data formats and improves input processing versatility.

Programming errors in Java generally fall into three categories: syntax errors, runtime errors, and logical errors. Syntax errors occur when code violates the grammar rules of the Java language, such as missing semicolons, and are detected by the compiler . Runtime errors occur during execution; a typical example is a divide by zero error. Logical errors are more subtle, as they do not prevent program execution but result in incorrect outcomes, like applying a wrong formula . Detecting logical errors requires thorough testing and debugging. Effective use of development tools and knowledge of error types can help identify and resolve these errors.

Error detection and debugging are critical in the software development process to ensure Java programs function correctly beyond just compiling. While syntax errors prevent compilation and are readily fixed, logical and runtime errors, such as incorrect computations or unhandled exceptions, pose subtler challenges as they do not stop compilation and might only surface during execution . Thus, ensuring a program compiles without errors doesn't guarantee its correctness; thorough testing, logical analysis, and debugging tools are essential to identify and resolve these deeper defects, thus achieving a fully functional program.

Custom input parsing with Java's Scanner involves setting specific delimiters and reading data tokens as needed. Pseudo-code for parsing a CSV line using commas as delimiters: 1. Import Scanner and set `Scanner sc = new Scanner(inputString);` 2. Use `sc.useDelimiter(",");` to set comma as the delimiter. 3. Iterate with `while(sc.hasNext()){` 4. Retrieve tokens with `String value = sc.next();` 5. Process each token as needed. This illustrates dynamic input parsing to efficiently handle complex or non-standard inputs by redefining token boundaries to suit specific file formats or data streams .

The import statement and package structure in Java are vital for maintainability and scalability. They enable a modular approach to programming, where code is organized into reusable components. Import statements like import java.util.*; streamline the inclusion of utilities, reducing code complexity and fostering reuse . This organization allows easy updates, facilitates collaboration among developers, and adapts to growing software needs by seamlessly integrating new modules without disrupting existing code. Consequently, a well-structured package system and strategic use of import statements enhance both code clarity and project scalability.

Effective testing of Java programs for logical and syntax errors involves a mix of automated tools and manual testing. Unit tests systematically examine individual components for correct functionality, revealing both logical and syntax issues. Tools like JUnit facilitate this process with easily repeatable test cases. Code reviews and static analysis detect errors by scrutinizing code against best practices and language rules. Additionally, debugging tools like breakpoints help trace and fix runtime errors. Integrating continuous integration systems ensures regular testing after code changes, maintaining robustness and accuracy through constant verification and validation .

The import statement in Java allows the inclusion of specific classes or entire packages into a program, facilitating modular code organization and reuse. By importing packages such as java.util.*, a programmer can easily integrate various utility classes without rewriting them, promoting flexibility and maintainability . An example of using an import statement is: import java.util.Scanner; which enables the use of the Scanner class for input operations . This approach simplifies code and enhances functionality by leveraging existing library classes.

In the Java Scanner class, next() reads the next complete token from the scanner, which can be a word or number depending on delimiters . nextLine() reads a whole line from the input, treating newline characters as delimiters, perfect for input with spaces. hasNext() is a boolean method that checks if there are more tokens available, helping control input loops . These methods serve distinct input-processing needs, with nextLine() ideal for full lines, next() for tokens, and hasNext() for iterative checks.

Logical errors result in incorrect program output despite successful compilation and no runtime errors. Addressing them requires scenario-based testing to compare expected and actual outcomes. For instance, consider a program intended to calculate rectangle area but mistakenly programmed to compute the perimeter. Test cases using known inputs and comparing calculated vs. expected area results can reveal the error . This scenario emphasizes how defining precise test cases, verifying against intended logic, and applying debugging insights can effectively identify and rectify logical programming errors.

You might also like