Chapter 11

More on Basic Input/Output

I. Fill in the blanks:

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

2. ______________package is necessary to be imported in order to use Scanner class.

3. Token is a set of characters separated by ______________

4. The default limiter used in Scanner object is _____________

5. System.in receives the input from the ________________for the Scanner object.

6. Method _________________can be used to accept a token from Scanner object.

7. ______________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 ________________

9. _________________is the method used to check whether the next token is a boolean type value or not.

10. _______________number of objects can be input into a Scanner object.

Ans.

1. Scanner

2. java.util

3. delimiter

4. whitespace

5. keyboard or console

6. next( )

7. nextInt( )

8. hasNextFloat( )

9. hasNextBoolean( )

10. one

II. Write TRUE or FALSE:

1. Scanner class is a useful package of JDK1.5

2. Strings can even be input without using Scanner object

3. The word ‘new’ is a keyword to create any object.

4. You need not be aware about the number of tokens to be input to a Scanner object.

5. You can terminate a String even by using carriage return.

6. nextFloat can also accept an integer token.

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

8. nextInt( )can be used to accept an exponential value.

Ans.

1. true

2. true

3. true

4. true

5. true

6. false

7. true

8. false

III. Answer the following:

1. What do you mean by Scanner class?

Ans. Scanner class is available in the system package java.util. This package must be imported to avail the facilities contained in the Scanner class. The Scanner class basically works on the principle of ‘tokens’ in the set of values input from the console. Characters like comma, semicolon, full stop, whitespace etc are used as delimiters or token separators.

2. Write syntax along with an example to create a Scanner object.

Ans. The syntax to create a Scanner object is as shown below:

Scanner sn = new Scanner(System.in);

The parameter System.in allows the constructor to receive data from the keyboard.

3. Mention the syntax to use ‘?’ as a token delimiter.

Ans. The default delimiter is whitespace but other delimiters can also be set for the Scanner object in order to separate the tokens. This is done as follows:

Scanner ob = new Scanner(System.in);

ob.useDelimiter(“ ?”);

4. Write down the use of nextInt( )method.

Ans. It receives the next token which can be expressed as an integer from the Scanner object. It is stored in an integer type variable.

Syntax

Scanner sn = new Scanner(System.in);

int k = sn.nextInt( );

5. What is the application of hasNextBoolean( ) method?

Ans. This function is used as follows:

boolean b = sn.hasNextBoolean( );

The variable ‘b’ returns true if the next token received from the Scanner object is a boolean type value. Otherwise it returns false.

6. Name the package which can be imported to allow the use of Scanner class.

Ans.  The package needed to import the Scanner class is, java.util

7. In what way can the following data be read from the Scanner object?

a) Integer type  b) Float type  c) Double type  d) String type  e) Boolean type

Ans.

                                                           Return type         method

a) Integer type                                  int                         nextInt( )

b) Float type                                     long                      nextLong( )

c) Double type                                   double                   nextDouble( )

d) String type                                     String                    next( )  

                                                                                    [for input of word ]

                                                           String                    nextLine( )                                                                                      [for input of sentence ]

e) Boolean type                                  boolean                 nextBoolean( )

IV. Differentiate between the following:

1. Scanner object and BufferedReader object

Ans.

BufferedReader

i) BufferedReader can read only String.

ii) It has a significantly large buffer ( temporary memory space ) of about 8KB.

Scanner

i) The Scanner object is a much more powerful than the BufferedReader object. It can parse the user input and read int, short, byte, long, float, double also apart from reading String.

ii) The Scanner has a lesser buffer (1KB) and is used for shorter inputs.

2. nextFloat( ) and nextDouble( )

Ans.

nextFloat( )      : It receives and returns the token as a float data type.

nextDouble( )   : It receives and returns the token as a double data type.

3. next( )and nextLine( )

Ans.

next( )         : The next( ) function is used to input a single word or a single alphanumeric token.

nextLine( )  :The nextLine( ) function is used to accept a String as a text line. i.e. It returns the rest of the current line, excluding any separator at the end.

4. hasNext( ) and hasNextLine( )

Ans.

hasNext( )          : It returns true if the Scanner object has another token in its input, false otherwise.

hasNextLine( )   : It returns true if the Scanner object has another line in its input, false otherwise.

5. hasNextInt( )and hasNextBoolean( )

Ans.

hasNextInt( )            : This function returns true if the next token can be expressed as an integer value. It returns false otherwise.

hasNextBoolean( )   : This function is used to check whether a token possessed by a Scanner object is of boolean type or not.

                             It returns either true or false.

V. Unsolved Programs:  

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.

Solution:

import java.util.*;

class Q1

{ public static void main(String[] LJP)

{Scanner ob=new Scanner(System.in);

String s;double temp;

System.out.println(“Enter the temperature(s) in Fahrenheit”);

while(true)

s=ob.next();

temp=Double.parseDouble(s);

temp=(temp*1.8)+32;

System.out.println(“Temperature in Celsius is “+temp);

if(ob.hasNextDouble()==false)

{ System.out.println(“Non numeric character entered”);

System.exit(0);

}}}}

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.

Solution:

import java.util.Scanner;

public class Q2 {

static void max_min()

{

Scanner ob=new Scanner(System.in);

int max,min,x;

System.out.println(“Enter 50 integers”);

max=ob.nextInt();

min=max;

for(int i=1;i<=49;i++)

{

x=ob.nextInt();

if(x>max)

max=x;

else if(x<min)

min=x;

}   

System.out.println(“The greatest number is :”+max);

System.out.println(“The smallest number is :”+min);

}}

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

Sample Output:     *                                                 * * * * *

                                   * *                                             * * * *

                                   *   *   *                                       * * *

                                   *   *   *   *                                  * *                           

                                   *   *   *   *   *                             *

Solution:

import java.util.*;

public class Q3

{  public static void main(String az[])

   {char ch;

    Scanner ob=new Scanner(System.in);

    System.out.println(“Enter your token to generate the pattern”);

    ch=ob.next().charAt(0);

    System.out.println(“Enter choice..1 for Triangle / 2 for Inverted Triangle”);

    switch(ob.nextInt())

    {case 1:System.out.println(“Pattern: Triangle”);

            for(int i=0;i<5;i++)

            {   for(int j=0;j<=i;j++)

                System.out.print(ch);

             System.out.println();

            }

            break;

     case 2:System.out.println(“Pattern: Inverted Triangle”);      

           for(int i=5;i>0;i–)

           {      for(int j=0;j<i;j++)

                  System.out.print(ch);

              System.out.println();

           }

}}}

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’.

Solution:

import java.util.Scanner;

public class Q4

{ public static void main(String g[])

{ String s=””;

int t=0,f=0;

Scanner sn=new Scanner(System.in);

System.out.println(“Answer true/false..Type exit to quit”);  

while(sn.hasNext()==true)

{

s=sn.next();

if(s.equalsIgnoreCase(“true”))         

t++;

else if(s.equalsIgnoreCase(“false”))

f++;

else

break;

}

System.out.println(“Count of True:”+t+”  Count of false:”+f);

}}

5) Write a program to accept a sentence in a 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                        

Solution:

import java.util.*;

public class Q5

{public static void main(String args[])

{Scanner ob=new Scanner(System.in);

char ch;

int cnt=0;

String s,wrd=””;

System.out.println(“Enter the String”);

s=ob.nextLine();

s=s.toLowerCase()+” “;

System.out.println(“Frequency of vowels in each word”);

System.out.println(“\n\nWords \t Frequency”);

for(int i=0;i<s.length();i++)

{   ch=s.charAt(i);

if(ch!=’ ‘)

wrd=wrd+ch;

if(ch==’a’||ch==’e’||ch==’i’||ch==’o’||ch==’u’)

cnt++;

}

else

System.out.println(wrd+”\t”+cnt);

wrd=””;

cnt=0;     //reset wrd and cnt for the next word

}

}}}

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

Solution:

import java.util.*;

public class Q6

{ public static void main(String h[])

{   String s=””,s1=””,w=””;

int cnt=0,max=0;

Scanner sn=new Scanner(System.in);

System.out.println(“Enter a sentence”);

s=sn.nextLine()+” “;

for(int j=0;j<s.length();j++)

{  if(s.charAt(j)!=’ ‘)

s1+=s.charAt(j);

cnt++;     

}

else

{  if(cnt>=max)

{

max=cnt;

w=s1;

}

s1=””;

cnt=0;

}

}

System.out.println(“The Longest Word: “+w);

}}

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.

Solution:

import java.util.*;

public class Q7

{public static void main(String h[])

{String s=””,s1=””;

int total=0;

Scanner sn=new Scanner(System.in);

System.out.println(“Total of Ascii Code of each word”);

System.out.println(“Enter a sentence”);

s=sn.nextLine()+” “;

for(int j=0;j<s.length();j++)

{  if(s.charAt(j)!=’ ‘)

{ s1=s1+s.charAt(j);

total+=s.charAt(j);

}

else

{ System.out.println(s1+”\t”+total);

s1=””;

total=0; //reset to 0

}}}}

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.

Sample Input:   1, 5, -2, 6, -3, -5, 8, -4, 9, 12

Sample Output:-2,-3, -5, -4, 1, 5, 6, 8, 9, 12

Solution:

import java.util.Scanner;

class Q8 {

static void main()

{ int num;

String s1=””,s2=””;

Scanner sn=new Scanner(System.in);

System.out.println(“Enter the positive and negative integers”);

System.out.println(“Enter 0 to quit”);

while(true)

{

num=sn.nextInt();

if(num<0)

s1=s1+”\n”+num;

else if(num>0)

s2=s2+”\n”+num;

else

break;

}

System.out.println(s1+” “+s2);

}}

9) Write a program to generate random numbers between 1 to N by using Scanner class taking N from the console.

Solution:

import java.util.*;

class Q9

{ static void generateNumber()

{Scanner ob=new Scanner(System.in);

int N;

System.out.println(“Enter the number”);

N=ob.nextInt();

System.out.println(“RANDOM NUMBER GENERATION”);

for(int i=0;i<=N;i++)

System.out.println((int)(Math.random()*N)+1);

}}

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 the token ‘THE’. The new String is:

COLD WATER AND HOT WATER GLASSES ARE KEPT ON TABLE.

Solution:

import java.util.Scanner;

public class Q10

{ static void wordChange()

  {String s=””;

   Scanner ob=new Scanner(System.in);

   System.out.println(“Enter a sentence”);

   s=ob.nextLine().toLowerCase();

   s=s.replace(“the”,””);

   System.out.println(“\n”+s);

}}

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

Solution:

import java.util.Scanner;

public class Q11

{

static void changeCase()

String s,wd=””;

char c1,c2;

Scanner sn=new Scanner(System.in);

System.out.println(“Enter a sentence”);

s=sn.nextLine();

s=s+” “;  

for(int i=0;i<s.length();i++)

{if(s.charAt(i)!=’ ‘)  

wd=wd+s.charAt(i);  

else

{   

c1=wd.charAt(0);                                //First char of the word

c2=wd.charAt(wd.length()-1);             //Last char of the word

if(Character.isUpperCase(c1) && Character.isLowerCase(c2) )

System.out.print(wd+” “);      

wd=””;                                                 //CLEAR s1

}}}}

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

Solution:

import java.util.Scanner;

public class Q12

{ static void pickLetters()

{ String s=””;

Scanner ob=new Scanner(System.in);

System.out.println(“Enter a sentence”);

s=ob.nextLine();

s=” “+s;             

for(int i=0;i<s.length();i++)

{ if(s.charAt(i)==’  ‘)                            //LOCATES SPACE

System.out.print(s.charAt(i+1));         

}

}}

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”    

                                                                                      [ICSE 2006]

Solution:

import java.util.Scanner;

public class Q13

{ public static void main(String g[])

{

String s=””;

Scanner ob=new Scanner(System.in);

System.out.println(“Enter a sentence terminated by a space and .”);

s=ob.nextLine();

s=s.toUpperCase();

s=s.replace(“26″,”15”);

s=s.replace(“JANUARY”,”AUGUST”);

s=s.replace(“REPUBLIC”,”INDEPENDENCE”);

System.out.println(s);

}}

14) Write a program by using Scanner class to input the 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

Solution:

import java.util.Scanner;

public class Q14 {

public static void main(String h[])

{ Scanner scn=new Scanner(System.in);

double p,r,t,a,ci;

System.out.println(“Enter Principal,Rate and Time”);

p=scn.nextDouble();

r=scn.nextDouble();

t=scn.nextInt();

a=p * Math.pow((1+r/100),t);

ci=a-p;

System.out.println(“Amount=Rs.”+a);

System.out.println(“Compound Interest=Rs.”+ci);

}}

********

%d bloggers like this: