Reputation: 17
so I'm developing this Java program which I need to iterate through a string of character and I just want to return back a character in which it contains (F or f or S or s or B or b or or L or l) in which if there is duplicate of the character found in the string it just take take ealiest character found. I'm just a beginner so please help me. this is what I can have so far. Thanks for your time
command ="France";
public static char CommandRestrictor (String command)
{
for(int i=0; i<command.length();i++)
{
char result=command.charAt(i); //set variable character char_bin to binary value in place of i
if(result=='F'||result=='f'||result=='L'||result=='l'||result=='S'||result=='s'||result=='B'||result=='b'||result=='r'||result=='R') {
return ;
}
else {
return 'f';
}
}
return result;
}
input result: "France"; output result: 'F'
Upvotes: 0
Views: 189
Reputation: 59
Your result variable is instantiated within the for loop, and so it is only accessible within the for loop. I would suggest the following:
public static char CommandRestrictor (String command)
{
char result = 'f';
for(int i = 0; i < command.length(); i++)
{
if(command.charAt(i)=='F'||command.charAt(i)=='f'||
command.charAt(i)=='L'||command.charAt(i)=='l'||
command.charAt(i)=='S'||command.charAt(i)=='s'||
command.charAt(i)=='B'||command.charAt(i)=='b'||
command.charAt(i)=='r'||command.charAt(i)=='R')
{
result = command.charAt(i);
break;
}
}
return result;
}
EDIT: Silly mistake. My if loop conditions said result=='F' rather than command.charAt(i)=='F'.
Upvotes: 1
Reputation: 79580
Do it as follows:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String[] testStrs = { "A football", "A Football", "A lamp", "A ball", "A Ball" };
for (String str : testStrs) {
System.out.println(commandRestrictor(str));
}
}
public static char commandRestrictor(String command) {
char ch = '\0';
Pattern pattern = Pattern.compile("[FfSsBbLl]");
Matcher matcher = pattern.matcher(command);
if (matcher.find()) {
ch = command.charAt(matcher.start());
}
return ch;
}
}
Output:
f
F
l
b
B
Upvotes: 1