问题
I have a list of strings consisting of tokens separated by spaces stored in an ArrayList. I need to scan if the tokens in string 1 are present in string 2. I managed to use Scanner to scan for the tokens. However, the Scanner doesn't do what I wanted.
I need suggestions/advice on
1. [EDITED] Example: there's one NN token in String 1 but there's two NN tokens in String
2. So, the Scanner should scan String 2 for NN token. With the code I gave, the Scanner will search for all NN tokens, including the second NN token. It should stop at the first NN token and not continue scanning for all NN tokens. {Haley's advice on break does stop the Scanner}
2. [EDITED] Now, the other problem is - if String 1 has two NN tokens, the Scanner should be smart enough to skip all the tokens found in previous scans. The Scanner should be able to match the second NN token in String 1 to the second NN token in String 2.
This is what I have so far..
import java.util.ArrayList;
import java.util.Scanner;
public class TokenMatching {
public static void main(String[] args)
{
ArrayList<String> taggedArray = new ArrayList<String>();
//Example how the string would look like
String string1 = "WRB VBD NN VB IN CC RB VBP NNP";
String string2 = "WRB NN MD PRP VB DT NN IN NNS POS JJ NNS";
taggedArray.add(string1);
taggedArray.add(string2);
//Nested for loop to match taggedArray(i) with taggedArray(j)
for(int i = 0; i< taggedArray.size(); i++)
{
for(int j = i + 1; j < taggedArray.size(); j++)
{
Scanner scan1 = new Scanner(taggedArray.get(i));
int index1 = 0;
while(scan1.hasNext())
{
String token1;
token1 = scan1.next();
System.out.println(token1);
Scanner scan2 = new Scanner(taggedArray.get(j));
int index2 =0;
while(scan2.hasNext())
{
String token2 = scan2.next();
if(token1.equals(token2))
{
int relPosition;
relPosition = Math.abs(index1-index2);
//The print lines help me keep track of what is going on in the loop
System.out.println("Match found.");
System.out.println("Relative position for " + token1 + " : " + relPosition);
}
else
{
System.out.println("No Match Found.");
}
index2++;
}
index1++;
}
}
}
}
}
Any advice would be a great help. Thank you.
回答1:
- Is there a way to make the Scanner scan for the first occurrence ONLY and move to the next token in string 1
In your if(token1.equals(token2))
add a break;
after System.out.println("Relative position for " + token1 + " : " + relPosition);
. Is the output generated by http://ideone.com/2o5Yz what you want?
回答2:
why not use
String[] tokens1 = string1.split("\\ ");
String[] tokens2 = string2.split("\\ ");
Now you can directly manupulate on arrays.
来源:https://stackoverflow.com/questions/12279214/java-how-to-get-scanner-to-match-the-first-occurence-only-and-skip-if-it-has-be