KnowledgeBoat Logo

Chapter 11

More on Basic Input/Output

Class 9 - APC Understanding Computer Applications with BlueJ


Fill in the blanks

Question 1

JDK1.5 allows a special class to input from the console. This class is termed as Scanner class.

Question 2

java.util package is necessary to be imported in order to use scanner class.

Question 3

Token is a set of characters separated by delimiters.

Question 4

The default delimiter used in scanner object is whitespace.

Question 5

System.in receives the input from the keyboard for the scanner object.

Question 6

Method next() can be used to accept a token from scanner object.

Question 7

nextInt() method reads a token as an integer.

Question 8

The method which checks whether the next token of the scanner object is a floating type value or not is hasNextFloat().

Question 9

hasNextBoolean() is the method used to check whether the next token is a boolean type value or not.

Question 10

Any number of objects can be input into a scanner object.

Write TRUE or FALSE

Question 1

Scanner class is a useful package of JDK 1.5.
False

Question 2

Strings can even be input without using scanner object.
True

Question 3

The word 'new' is a keyword to create any object.
True

Question 4

You need not be aware about the number of tokens to be input to a scanner object.
True

Question 5

You can terminate a string even by using carriage return.
True

Question 6

nextFloat can also accept an integer token.
True

Question 7

hasNextInt( ) results in true if the next token can be interpreted as an integer.
True

Question 8

nextlnt() can be used to accept an exponential value.
False

Answer the following

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

Differentiate between the following

Question 1

Scanner object and BufferedReader object

Scanner objectBufferedReader object
Scanner class parses the tokens into specific types like short, int, float, boolean, etc.BufferedReader just reads the stream and does not do any special parsing.
It is slower than BufferedReader.It is faster than Scanner.
It was introduced in JDK1.5It was introduced in JDK1.1

Question 2

nextFloat( ) and nextDouble( )

nextFloat( )nextDouble( )
It reads the next token entered by the user as a float value.It reads the next token entered by the user as a double value.

Question 3

next( ) and nextLine( )

next( )nextLine( )
It reads the next complete token from the Scanner object.It reads the complete line from the Scanner object.

Question 4

hasNext( ) and hasNextLine( )

hasNext( )hasNextLine( )
Returns true if the Scanner object has another token in its input.Returns true if there is another line in the input of the Scanner object.

Question 5

hasNextInt( ) and hasNextBoolean( )

hasNextInt( )hasNextBoolean( )
Returns true if the next token in the Scanner's input can be interpreted as an int value using the nextInt() method.Returns true if the next token in the Scanner's input can be interpreted as a boolean value.

Solutions to Unsolved Java Programs

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 KboatTemperatureConvert
{
    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: ");
        }
    }
}
Output
BlueJ output of KboatTemperatureConvert.java

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 KboatSmallLargeNumber
{
    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);
    }
}
Output
BlueJ output of KboatSmallLargeNumber.java
BlueJ output of KboatSmallLargeNumber.java

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 KboatPattern
{
    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;
        }
    }
}
Output
BlueJ output of KboatPattern.java
BlueJ output of KboatPattern.java

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 KboatCompetitiveExam
{
    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);
    }
}
Output
BlueJ output of KboatCompetitiveExam.java

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 KboatVowelFrequency
{
    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);
        }

    }
}
Output
BlueJ output of KboatVowelFrequency.java

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 KboatLongestWord
{
    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());
    }
    
}
Output
BlueJ output of KboatLongestWord.java

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 KboatWordSum
{
    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);
        }
    }
}
Output
BlueJ output of KboatWordSum.java

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 KboatNumbers
{
    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);
    }
}
Output
BlueJ output of KboatNumbers.java

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 KboatRandomNumbers
{
    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);
    }
}
Output
BlueJ output of KboatRandomNumbers.java

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 KboatRemoveThe
{
    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 + " ");
        }
    }
}
Output
BlueJ output of KboatRemoveThe.java

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 KboatDisplayTokens
{
    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 + " ");
        }
    }
}
Output
BlueJ output of KboatDisplayTokens.java

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 KboatInitials
{
    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));
        }
    }
}
Output
BlueJ output of KboatInitials.java

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 KboatWordReplace
{
    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 + " ");
                
        }
    }
}
Output
BlueJ output of KboatWordReplace.java

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 KboatCI
{
    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);
        }
    }
}
Output
BlueJ output of KboatCI.java
PrevNext