Java Scanner Usage getLineStartingWith(Scanner scanner, String starts)

Here you can find the source of getLineStartingWith(Scanner scanner, String starts)

Description

Return the line starting with starts using the given scanner.

License

Apache License

Parameter

Parameter Description
scanner The scanner to search in.
starts The String we search a line starting with.

Return

The first line starting with starts in the scanner else an empty String if there is no line starting with starts.

Declaration

public static String getLineStartingWith(Scanner scanner, String starts) 

Method Source Code


//package com.java2s;
/*/*from ww w  .j a  v a 2s. c om*/
 * Copyright JTheque (Baptiste Wicht)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Scanner;

public class Main {
    /**
     * Return the line starting with starts using the given scanner. The scanner will be closed if we read all the
     * lines.
     *
     * @param scanner The scanner to search in.
     * @param starts  The String we search a line starting with.
     *
     * @return The first line starting with starts in the scanner else an empty String if there is no line starting with
     *         starts.
     */
    public static String getLineStartingWith(Scanner scanner, String starts) {
        if (scanner != null) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();

                if (line.startsWith(starts)) {
                    scanner.close();

                    return line;
                }
            }

            scanner.close();
        }

        return "";
    }
}

Related

  1. getInput(Scanner in, String message, boolean allowNull)
  2. getInt()
  3. getInt(Scanner sc)
  4. getInteger(String parameter)
  5. getLines(String str)
  6. getLngIn()
  7. getNextInput(Scanner scan)
  8. getNextLine(final Scanner scanner)
  9. getNextLine(final Scanner source)