Reputation: 69
I do understand that I might find another threads/topics about "Duplicated characters in a string" but they all are completely different from my question.
I have created a simple hangman game, where I input the words I'm gonna use to play with, but if I enter a a word that has a duplicated character, my whole program becomes useless and doesn't work properly. I do understand why it does so, because of the indexOf method, but I don't know how to fix it.
Thanks in advance.
Here's the code:
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Welcome to the Hangman game..");
System.out.println("Enter the words you want to play with, '.' to exit");
ArrayList <String> x=new ArrayList<String>();
x.add(s.nextLine());
for(int i=0;!(x.get(i).contains(".") && x.get(i).lastIndexOf(".")==x.get(i).length()-1);i++){
x.add(s.nextLine());
}
x.set(x.size()-1, x.get(x.size()-1).substring(0, x.get(x.size()-1).length()-1));
System.out.println("Okay, a word will be chosen randomly, try to guess it!");
Random rand = new Random();
int value = rand.nextInt(x.size()==1 ? x.size():x.size()-1)+0;
char[] chr=new char[x.get(value).length()];
for(int i=0;i<chr.length;i++){
chr[i]='-';
System.out.print(chr[i]);
}
char m;
int n;
Boolean r=true;
while(r){
m = s.next().charAt(0);
n=x.get(value).indexOf(m);
if(n!=-1)
chr[n]=m;
for(int j=0;j<chr.length;j++){
System.out.print(chr[j]);
}
if(new String(chr).indexOf('-') == -1){
r=false;
System.out.println("\nHangman!");
}
}
}
Upvotes: 0
Views: 94
Reputation: 2578
There is an indexOf method that takes two parameters, the character, and the index to start the search from. Calling it in a loop will reveal every occurrence of the given character.
Istead of
n=x.get(value).indexOf(m);
if(n!=-1)
chr[n]=m;
You could write
int n = x.get(value).indexOf(m);
while(n!=-1) {
chr[n] = m;
n = x.get(value).indexOf(m, n + 1);
}
Upvotes: 1
Reputation: 1584
You can do something like this
String word = "thisandthat";
int pointer = 0;
List<Integer> tPositions = new ArrayList<>();
while((pointer=word.indexOf("t", pointer))!=-1){
tPositions.add(new Integer(pointer++));
}
After the loop is finished it will have found all of the positions of "t" in the string. This is because indexOf()
can take two parameters the first being the search string and the second being the index to start from. When the search string does not exist in the testable area indexOf()
returns -1
Oh and you have to increment pointer by one:
tPositions.add(new Integer(pointer++));
otherwise you will fall into an infinite loop because it will just continue to find the instance of the specified character.
Upvotes: 1