Search This Blog

Sunday, January 30, 2011

Question 21

What is the result of attempting to compile and run the given code?

import java.util.*;
public class ScannerDelimiter2 {
  public static void main(String[] args) {
    String input = "10 Apples 20 Oranges 30 Pears";
    Scanner s = new Scanner(input).useDelimiter("\\d");
    String str[] = new String[6];
    int i=0;
    while(s.hasNext()){
      str[i]=s.next();
      System.out.println(str[i++]);
    }
  }
}
Options:


a. Prints "apples", "oranges", "pears" in separate lines.
b. Prints "10", "apples", "20", "oranges", "30", "pears" in separate lines.
c. Exception thrown at runtime.
d. Code does not compile.
e. None of these



Answer : A

The pattern \d corresponds to finding a digit from 0-9. In the code the string has 6 digits. So the split happens in this way.

1<>0< Apples >2<>0< Oranges >3<>0< Pears>

<>
< Apples >
<>
< Oranges >
<>
< Pears>


Based on the above illustration all the other options are incorrect.


Java API for reference.


image

Question 21SocialTwist Tell-a-Friend

No comments:

Post a Comment