Categories
Class 9

More on Basic Input/Output

Fill in the blanks:

  1. JDK 1.5 allows a special class to input from the console. This class is termed as Scanner class.
  2. java.util package is necessary to be imported in order to use Scanner class.
  3. Token is a set of characters separated by delimiters.
  4. The default delimiter used in Scanner object is white space.
  5. System.in receives the input from the keyboard for the Scanner object.
  6. Method next() can be used to accept a token from Scanner object.
  7. nextInt() method reads a token as an integer.
  8. The method which checks whether the next token of the Scanner object is a floating type value or not is nextFloat().
  9. nextBoolean() is the method used to check whether the next token is a boolean type value or not.
  10. Any number of objects can be input into a Scanner object.

Write True or False:

  1. Scanner class is a useful package of JDK 1.5. (True)
  2. Strings can even be input without using Scanner object. (True)
  3. The word ‘new’ is a keyboard to create any object. (True)
  4. You need not be aware about the number of tokens to be input to a Scanner object. (True)
  5. You can terminate a string even by using carriage return. (True)
  6. nextFloat() can also accept an integer token. (True)
  7. hasNextInt() results in true if the next token can be interpreted as an integer. (True)
  8. nextInt() can be used to accept an exponential value. (False)

Answer the following:

  1. What do you mean by Scanner class?
    The Scanner class allows the users to input the values of various data types.
  2. Write the syntax along with an example to create a Scanner object.
    Syntax: Scanner <object name> = new Scanner(System.in);
    Example: Scanner in = new Scanner(System.in);
  3. Mention the syntax to use ‘?’ as a token delimiter.
    sc.useDelimiter("?"); where ‘sc’ is the Scanner object.
  4. Write down the use of nextInt() method.
    It receives the next token which can be expressed as an integer type from the Scanner object.
  5. What is the application of hasNextBoolean() method?
    It returns true if the next token can be expressed as a boolean type value, otherwise it returns false.
  6. Name the package which can be imported to allow the use of Scanner class.
    java.util package
  7. In what way can the following data be read from the Scanner object?
    a) Integer type
    int i = sc.nextInt();
    b) Float type
    float f = sc.nextFloat();
    c) Double type
    double d = sc.nextDouble();
    d) String type
    String s = sc.nextLine();
    e) Boolean type
    boolean b = sc.nextBoolean();

Differentiate between the following

  1. Scanner object and BufferedReader object:
    Scanner object is built using the Scanner class which is in java.util package. BufferedReader object is built using the BufferedReader class which is available in java.io package.
  2. nextFloat() and nextDouble():
    nextFloat() receives the next token which can be expressed as an float type from the Scanner object. nextDouble() receives the next token which can be expressed as an double type from the Scanner object.
  3. next() and nextLine():
    next() accepts the next token which is a string from the Scanner object. nextLine() accepts a token as a string through the Scanner object.
  4. hasNext() and hasNextLine():
    hasNext() returns true if the Scanner object has another token in its input, otherwise it returns false. hasNextLine() returns true if the Scanner object has another line in its input, otherwise it returns false.
  5. hasNextInt() and hasNextBoolean():
    hasNextInt() returns true if the next token in the Scanner object can be interpreted as an int type. hasNextBoolean() returns true if the next token can be expressed as a boolean type, otherwise it returns false.

Unsolved Programs

Question 1: Using Scanner class, write a program to input temperatures recorded in different cities in Fahrenheit. Convert and print each temperature in Celsius. The program terminates when the user enters a non-numeric character.

import java.util.Scanner;
class Temperature{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.print("Temperature in Fahrenheit: ");
        while(sc.hasNextDouble()){
            double f = sc.nextDouble();
            double c = 5.0 / 9 * (f - 32);
            System.out.println("In celsius: " + c);
        }
    }
}

Question 2: Write a program to accept a set of 50 integers. Find and print the greatest and the smallest numbers by using the Scanner class method.

import java.util.Scanner;
class Find{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int small = 0;
        int large = 0;
        for(int i = 1; i <= 5; i++){
            System.out.print("Enter the number: ");
            int num = sc.nextInt();
            if(i == 1){
                small = num;
                large = num;
            }
            if(small > num)
                small = num;
            if(large < num)
                large = num;
        }
        System.out.println("Smallest number: " + small);
        System.out.println("Largest number: " + large);
    }
}

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 1:
Enter your choice: 1
Output:
*
* *
* * *
* * * *
* * * * *

Sample Input 2:
Enter your choice: 2
* * * * *
* * * *
* * *
* *
*

import java.util.Scanner;
class Pattern{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your choice: ");
        int choice = sc.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;
        }
    }
}

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;
class Frequency{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.print("Number of questions: ");
        int n = sc.nextInt();
        sc.nextLine(); //to skip the newline
        int t = 0;
        int f = 0;
        for(int i = 1; i <= n; i++){
            System.out.print("Answer: ");
            String result = sc.nextLine();
            if(result.equalsIgnoreCase("True"))
                t++;
            else if(result.equalsIgnoreCase("False"))
                f++;
        }
        System.out.println("True: " + t);
        System.out.println("False: " + f);
    }
}

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.

import java.util.Scanner;
class Vowels{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the sentence: ");
        while(true){
            String s = sc.next();
            if(s.equals(".") || s.equals("?") || s.equals("!"))
                break;
            s = s.toUpperCase();
            int f = 0;
            for(int i = 0; i < s.length(); i++){
                char ch = s.charAt(i);
                switch(ch){
                    case 'A':
                    case 'E':
                    case 'I':
                    case 'O':
                    case 'U':
                    f++;
                }
            }
            System.out.println(s + " - " + f);
        }
    }
}

Question 6: Write a program using Scanner class to input a sentence. Display the longest word along with the number of characters in it.

import java.util.Scanner;
class Longest{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the sentence: ");
        String s = sc.nextLine();
        String longest = "";
        String word = "";
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(ch == ' ' || ch == '?' || ch == '!' || ch == '.'){
                if(longest.length() < word.length())
                    longest = word;
                word = "";
            }
            else
                word += ch;
        }
        int num = longest.length();
        System.out.println("The longest word: " + longest);
        System.out.println("Number of characters: " + num);
    }
}

Question 7: Write a program 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;
class Sum{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the sentence: ");
        while(true){
            String s = "";
            int a = 0;
            s = sc.next();
            if(s.equals("."))
                break;
            for(int i = 0; i < s.length(); i++)
                a += s.charAt(i);
            System.out.println(s + " - " + a);
        }
    }
}

Question 8: Write a program 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.
Sample Input: 1, 5, -2, 6, -3, -5, 8, -4, 9, 12
Sample Output: -2, -3, -5, -4, 1, 5, 6, 8, 9, 12

import java.util.Scanner;
class Numbers{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String pos = "";
        String neg = "";
        System.out.print("Enter the numbers: ");
        String s = sc.nextLine();
        sc = new Scanner(s);
        sc.useDelimiter(", ");
        while(sc.hasNextInt()){
            int t = sc.nextInt();
            if(t < 0)
                neg += t + ", ";
            else
                pos += t + ", ";
        }
        String result = neg + pos;
        System.out.println(result);
    }
}

8 replies on “More on Basic Input/Output”

Leave a Reply