What is the output for the below code ? public class Test { public static void main(String... args) { String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\s*fish\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); } }

  1. 1 2 red blue

  2. Compile Error - because Scanner is not defind in java.

  3. 1 fish 2 fish red fish blue fish

  4. 1 fish 2 fish red blue fish


Correct Option: A
Explanation:

To solve this question, the user needs to understand how the Scanner class works in Java and how the useDelimiter() method works.

The useDelimiter() method sets the delimiter pattern for the Scanner object to use when breaking down input into tokens. In this case, the delimiter pattern is set to "\s*fish\s*", which means that the Scanner object will split the input string whenever it encounters the word "fish" surrounded by any number of whitespace characters.

The code then uses the nextInt() and next() methods of the Scanner object to retrieve the tokens that were split from the input string.

Let's go through each option to determine the correct answer:

A. 1 2 red blue: This option is correct. The first call to nextInt() retrieves the integer "1" that comes before the first occurrence of "fish". The second call to nextInt() retrieves the integer "2" that comes after the first occurrence of "fish". The first call to next() retrieves the word "red", and the second call to next() retrieves the word "blue".

B. Compile Error - because Scanner is not defined in java.: This option is incorrect. The Scanner class is defined in Java, so this code will not produce a compile error due to the use of Scanner.

C. 1 fish 2 fish red fish blue fish: This option is incorrect. The code does not print out the entire input string, but rather it retrieves specific tokens from the input string using the nextInt() and next() methods.

D. 1 fish 2 fish red blue fish: This option is incorrect. The second call to nextInt() retrieves the integer "2", which comes after the first occurrence of "fish". The first call to next() retrieves the word "red", and the second call to next() retrieves the word "blue".

Therefore, the correct answer is:

The Answer is: A. 1 2 red blue

Find more quizzes: