简体   繁体   中英

Scanning 2 Different Data Types Java

I have a data file that is a list of names followed by "*****" and then continues with integers. How do I scan the names and then break with the asterisks, followed by scanning the integers?

This question might help : Splitting up data file in Java Scanner

Use the Scanner.useDelimiter() method, put "*****" as the delimiter, like this for example :

sc.useDelimiter("*****");

OR

Alternative :

  1. Read the whole string
  2. Split the string using String.split()
  3. Resulting String array will have index 0 contain the names and index 1 contain the integers.

Below code should work for you

    Scanner scanner = new Scanner(<INPUT_STR>).useDelimiter("[*****]");
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            // For Integer
        } else {
            // For String
        }
    }

Although this seems a tedious thing, I think this would solve the issue without worrying if the split returns anything, and the out of bounds.

final String x = "abc****12354";
    final Pattern p = Pattern.compile("[A-Z]*[a-z]*\\*{4}");
    final Matcher m = p.matcher(x);
    while (m.find()) {
        System.out.println(m.group());
    }
    final Pattern p1 = Pattern.compile("\\*{4}[0-9]*");
    final Matcher m1 = p1.matcher(x);
    while (m1.find()) {
        System.out.println(m1.group());
    }

The first pattern match minus the last 4 stars (can be substring-ed out) and the second pattern match minus the leading 4 stars (also can be removed) would give the request fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM