go to previous page   go to home page   go to next page

Answer:

S

System.out.println( ("Orange " + "Soda").charAt( 7 ) );

A temporary String object is created by the concatenation operator. The charAt() method of that object is invoked which returns the 7th character. The temporary object then becomes garbage.


Column Checker

import java.util.Scanner;
import java.io.*;

class ColumnCheck
{
  public static void main (String[] arg)
  {
    final int colNum = 10;
    int counter = 0;
    String line = null;
    Scanner scan = new Scanner( System.in );
   
    while ( scan.hasNext() )
    {    
      line = scan.nextLine() ;
      counter = counter +1;
      if ( line.length() > colNum && line.charAt( colNum ) != ' ' )
        System.out.println( counter + ":\t" + line );
    }    
  }
}    

Here is a program that checks that every line of a text file has a space character in column 10. This might be used to verify the correct formatting of columnar data or of assembly language source programs.

The program is used with redirection:

C:\>javac ColumnCheck.java

C:\>java ColumnCheck < datafile.txt

With input redirection, the operating system sends characters to the program from a file, not from the keyboard. Now when the program is running nextLine() reads one line from the file.

An improved program might ask the user for several column numbers to check.


QUESTION 17:

Will the program crash if a line has fewer than 10 characters? Inspect the statement

if ( line.length() > colNum && line.charAt( colNum ) != ' ' )
  System.out.println( counter + ":\t" + line );

How is the short-circuit nature of && used here?


go to previous page   go to home page   go to next page