Question 1
What do you mean by scanner class?
Scanner class is used to get user input in Java. It is defined in java.util package.
Question 2
Write syntax along with an example to create a scanner object.
Syntax
Scanner = new Scanner(System.in);
Example
Scanner in = new Scanner(System.in);
Question 3
Mention the syntax to use '?' as a token delimiter.
in.useDelimiter("\\?");
Here, 'in' is the Scanner class object
Question 4
Write down the use of nextInt() method.
It reads the next token entered by the user as an int value.
Question 5
What is the application of hasNextBoolean( ) method?
Returns true if the next token in the Scanner's input can be interpreted as a boolean value, otherwise it returns false.
Question 6
Name the package which can be imported to allow the use of scanner class.
java.util
Question 7
In what way can the following data be read from the scanner object?
(a) Integer type
int a = in.nextInt();
(b) Float type
float b = in.nextFloat();
(c) Double type
double c = in.nextDouble();
(d) String type
String str = in.nextLine();
(e) Boolean type
boolean d = in.nextBoolean();
Question 1
Scanner object and BufferedReader object
Scanner object
Scanner class parses the tokens into specific types like short, int, float, boolean, etc.
It is slower than BufferedReader.
It was introduced in JDK1.5
BufferedReader object
BufferedReader just reads the stream and does not do any special parsing.
It is faster than Scanner.
It was introduced in JDK1.1
Question 2
nextFloat( ) and nextDouble( )
nextFloat( )
It reads the next token entered by the user as a float value.
nextDouble( )
It reads the next token entered by the user as a double value.
Question 3
next( ) and nextLine( )
next( )
It reads the next complete token from the Scanner object.
nextLine( )
It reads the complete line from the Scanner object.
Question 4
hasNext( ) and hasNextLine( )
hasNext( )
Returns true if the Scanner object has another token in its input.
hasNextLine( )
Returns true if there is another line in the input of the Scanner object.
Question 5
hasNextInt( ) and hasNextBoolean( )
hasNextInt( )
Returns true if the next token in the Scanner's input can be interpreted as an int value using the nextInt() method.
hasNextBoolean( )
Returns true if the next token in the Scanner's input can be interpreted as a boolean value.
Question 1
Using scanner class, write a program to input temperatures recorded in different cities in °F (Fahrenheit). Convert and print each temperature in °C (Celsius). The program terminates when user enters a non-numeric character.
import java.util.Scanner;
public class TemperatureConvert
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Temperature in Fahrenheit: ");
while (in.hasNextDouble()) {
double t = in.nextDouble();
double ct = 5 / 9.0 * (t - 32);
System.out.println("Temperature in Celsius: " + ct);
System.out.print("Enter Temperature in Fahrenheit: ");
}
}
}
Question 2
Write a program to accept a set of 50 integers. Find and print the greatest and the smallest numbers by using scanner class method.
import java.util.Scanner;
public class SmallLargeNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 50 integers:");
int small = Integer.MAX_VALUE, big = Integer.MIN_VALUE;
for (int i = 1; i <= 50; i++) {
int n = in.nextInt();
if (n > big)
big = n;
if (n < small)
small = n;
}
System.out.println("Smallest Number = " + small);
System.out.println("Largest Number = " + big);
}
}
Question 3
Write a program (using scanner class) to generate a pattern of a token in the form of a triangle or in the form of an inverted triangle depending upon the user's choice.
Sample Input/Output:
Enter your choice 1
*
* *
* * *
* * * *
* * * * *
Enter your choice 2
* * * * *
* * * *
* * *
* *
*
import java.util.Scanner;
public class Pattern
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Triangle");
System.out.println("2. Inverted Triangle");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
switch (choice) {
case 1:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
break;
case 2:
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
break;
default:
System.out.println("Invalid Choice");
break;
}
}
}
Question 4
In a competitive examination, a set of 'N' number of questions results in 'True' or 'False'. Write a program by using scanner class to accept the answers. Print the frequency of 'True' and 'False'.
import java.util.Scanner;
public class CompetitiveExam
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of questions: ");
int n = in.nextInt();
int trueFreq = 0, falseFreq = 0;
System.out.println("Enter answers:");
for (int i = 1; i <= n; i++) {
boolean ans = in.nextBoolean();
if (ans)
trueFreq++;
else
falseFreq++;
}
System.out.println("True Frequency = " + trueFreq);
System.out.println("False Frequency = " + falseFreq);
}
}
Question 5
Write a program to accept a sentence in mixed case. Find the frequency of vowels in each word and print the words along with their frequencies in separate lines.
Sample Input:
We are learning scanner class
Sample Output:
Word Frequency of vowels
We 1
are 2
learning 3
scanner 2
class 1
import java.util.Scanner;
public class VowelFrequency
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence ending with a space & terminating with (.):");
while (in.hasNext()) {
String orgWord = in.next();
String word = orgWord.toUpperCase();
if (word.equals("."))
break;
int vowelFreq = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'A' ||
word.charAt(i) == 'E' ||
word.charAt(i) == 'I' ||
word.charAt(i) == 'O' ||
word.charAt(i) == 'U')
vowelFreq++;
}
System.out.println(orgWord + "\t\t" + vowelFreq);
}
}
}
Question 6
Write a program by using scanner class to input a sentence. Display the longest word along with the number of characters in it.
Sample Input:
We are learning scanner class in Java
Sample Output:
The longest word: learning
Number of characters: 8
import java.util.Scanner;
public class LongestWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
str += " ";
String word = "", lWord = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
if (word.length() > lWord.length())
lWord = word;
word = "";
}
else {
word += str.charAt(i);
}
}
System.out.println("The longest word: " + lWord);
System.out.println("Number of characters: " + lWord.length());
}
}
Question 7
Write a program by using scanner class to input a sentence. Print each word of the sentence along with the sum of the ASCII codes of its characters.
import java.util.Scanner;
public class WordSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence ending with a space & terminating with (.):");
while (true) {
String word = in.next();
if (word.equals("."))
break;
int sum = 0;
for (int i = 0; i < word.length(); i++) {
sum += (int)word.charAt(i);
}
System.out.println(word + "\t" + sum);
}
}
}
Question 8
Write a program by using scanner class to accept a set of positive and negative numbers randomly. Print all the negative numbers first and then all the positive numbers without changing the order of the numbers.
import java.util.Scanner;
public class Numbers
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type DONE to Stop Entering Numbers");
System.out.println("Enter Positive & Negative Numbers Randomly:");
String posStr = "", negStr = "";
while(in.hasNextInt()) {
int i = in.nextInt();
if (i < 0)
negStr += i + " ";
else
posStr += i + " ";
}
System.out.println(negStr + posStr);
}
}
Question 9
Write a program to generate random numbers between 1 to N by using scanner class taking N from the console.
import java.util.Scanner;
public class RandomNumbers
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter N: ");
int n = in.nextInt();
int r = (int)(Math.random() * n) + 1;
System.out.print("Random Number = " + r);
}
}
Question 10
Consider a String:
THE COLD WATER AND THE HOT WATER GLASSES ARE KEPT ON THE TABLE
Write a program by using scanner class to enter the string and display the new string after removing repeating token 'THE'. The new string is:
COLD WATER AND HOT WATER GLASSES ARE KEPT ON TABLE
import java.util.Scanner;
public class RemoveThe
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence ending with a space & terminating with (.):");
while(in.hasNext()) {
String word = in.next();
if (word.equals("."))
break;
else if (!word.toUpperCase().equals("THE"))
System.out.print(word + " ");
}
}
}
Question 11
Using scanner class, write a program to input a string and display all the tokens of the string which begin with a capital letter and end with a small letter.
Sample Input: The capital of India is New Delhi
Sample Output: The India New Delhi
import java.util.Scanner;
public class DisplayTokens
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence ending with a space & terminating with (.):");
while(in.hasNext()) {
String word = in.next();
if (word.equals("."))
break;
if (Character.isUpperCase(word.charAt(0)) &&
Character.isLowerCase(word.charAt(word.length() - 1)))
System.out.print(word + " ");
}
}
}
Question 12
Write a program to input a string by using scanner class. Display the new string which is formed by the first character of each string.
Sample Input: Automated Teller Machine
Sample Output: ATM
import java.util.Scanner;
public class Initials
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence ending with a space & terminating with (.):");
while (in.hasNext()) {
String word = in.next();
if (word.equals("."))
break;
System.out.print(word.charAt(0));
}
}
}
Question 13
Consider the following statement:
"26 January is celebrated as the Republic Day of India"
Write a program (using scanner class) to change 26 to 15; January to August; Republic to Independence and finally print as:
"15 August is celebrated as the Independence Day of India"
import java.util.Scanner;
public class WordReplace
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence ending with a space & terminating with (.):");
while (true) {
if (in.hasNextInt()) {
int n = in.nextInt();
if (n == 26)
System.out.print("15 ");
else
System.out.print(n + " ");
}
String word = in.next();
if (word.equals("."))
break;
else if (word.equals("January"))
System.out.print("August ");
else if (word.equals("Republic"))
System.out.print("Independence ");
else
System.out.print(word + " ");
}
}
}
Question 14
Write a program by using scanner class to input principal (P), rate (R) and time (T). Calculate and display the amount and compound interest. The program terminates as soon as an alphabet is entered.
Use the formula:
A = P(1 + (R / 100))T
CI = A - P
import java.util.Scanner;
public class CI
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an alphabet to exit");
double p = 0.0, r = 0.0, t = 0.0;
while (true) {
System.out.print("Enter principal: ");
if (in.hasNextDouble())
p = in.nextDouble();
else
break;
System.out.print("Enter rate: ");
if (in.hasNextDouble())
r = in.nextDouble();
else
break;
System.out.print("Enter time: ");
if (in.hasNextDouble())
t = in.nextDouble();
else
break;
double amt = p * Math.pow(1 + (r / 100), t);
double ci = amt - p;
System.out.println("Amount = " + amt);
System.out.println("Compound Interest = " + ci);
}
}
}