简体   繁体   中英

Java Scanner - Using conditions in scanner to check token type and splitting alphanumerals

I am trying to split two lines of strings inputted into the scanner as one big string, back into two separate strings (as shown with my below example and expected output).

Pseudo Code-ish Code

Scanner s = new Scanner("Fred: 18Bob D: 20").useDelimiter(":") //delimiter is probably pointless here
List<String> list = new ArrayList<>();
while (s.hasNext()) {
    String str = "";
    if (//check if next token is str) {
        str = str + s.next();
    }
    if (//check if next token is :) {
        //before the : will always be a name of arbitary token length (such as Fred, 
//and Bob D), I also need to split "name: int" to "name : int" to achieve this
        str = str + ": " + s.next();
    }
    if (//check if next token is alphanumeral) {
        //split the alphanumeral then add the int to str then the character
        str = str + s.next() + "\n" + s.next() //of course this won't work 
//since s.next(will go onto the letter 'D')
    }
    else {
        //more code if needed otherwise make the above if statement an else
    }
    list.add(str);
}
System.out.println(list);

Expected Output

Fred: 18
Bob D: 20

I just can't figure out how I can achieve this. If any pointers towards achieving this can be given, I would be more than thankful.

Also, a quick question. What's the difference between \\n and line.separator and when should I use each one? From the simple examples I've seen in my class codes, line.separator has been used to separate items in a List<String> so that's the only experience I have with that.

You can try below snippet for your purpose :

List<String> list = new ArrayList<String>();
String str="";
while(s.hasNext()){
    if(s.hasNextInt()){
        str+=s.nextInt()+" ";                                   
    }
    else {                          
        String tmpData = s.next();
        String pattern = ".*?(\\d+).*";
        if(tmpData.matches(pattern)){
            String firstNumber = tmpData.replaceFirst(".*?(\\d+).*", "$1");         
            str+=firstNumber;
            list.add(str);
            str="";
            str+=tmpData.replace(firstNumber, "")+" ";                                                  
        }else{
            str+=tmpData;
        }               
    }           
}
list.add(str);
System.out.println(list);

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