Break from a loop when a condition is true [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this:
for(String s : names){ //names is an ArrayList of strings
if( s.equals("bob") ){
//do sth and then break from the loop
break;
}
}
When the condition inside the if is true, I would expect the for-loop to break. But it doesn't.. what I code wrong?
EDIT:
the problem was that I have an extra for loop in my code
for( //a loop here){
for(String s : names){ //names is an ArrayList of strings
if( s.equals("bob") ){
//do sth and then break from the loop
break;
}
}
}
that's why the inside loop was executing after the break...

Code looks fine, there is some data issue in your list or difference of case in two strings . Try using equalsIgnoreCase instead of equals as suggested
It just prints hi, as soon as bob comes it breaks.
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("hi");
names.add("bob");
names.add("bye");
for (String s : names) {
if (s.equals("bob")) {
System.out.println("breaking...");
break;
} else {
System.out.println(s);
}
}
}
output
hi
breaking...

Related

How to apply the logic if the key in map is not found based on condition? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have following code :
for(String s1 : source){
for(String s2 : target){
if(s1.length() > 4 && s2.length() > 4){
String sKey = s1.substring(1,5);
String tKey = s2.substring(1,5);
if(sKey.equals(tKey)){
//Do your logic...
}else if(!sKey.equals(tKey) && sKey not availlable in the target list){
//print the value that sKey not availlable in target
}
}
}
}
I need to print the value if key is not found throughout the complete traversing of the list.
Please help !!
The obvious solution is to add a condition, and check that condition at the end.
for(String s1 : source){
boolean found = false;
for(String s2 : target){
if(s1.length() > 4 && s2.length() > 4){
String sKey = s1.substring(1,5);
String tKey = s2.substring(1,5);
if(sKey.equals(tKey)){
found=true;
break;
}
}
}
if(found){
//found logic
} else{
//not found logic
}
}
The problem with this, you are making a new sub-string each time. Instead I would suggest creating a list of keys.
List<String> targetKeys = target.stream().filter(
s->s.length()>4
).map(
s->s.substring(1,5)
).collect(Collectors.toList());
List<String> sourceKeys = source.stream().filter(
s->s.length()>4
).map(
s->s.substring(1,5)
).collect(Collectors.toList());
Then you can do things like.
sourceKeys.removeAll(targetKeys);
Where you would be left with only keys that don't exist.
Use the contains method from List
if (!targetList.contains(sKey)) {
// System.out.println("this will print only if the sKey not present in targetList");
}
If I get correctly what you are trying to do, this should do it:
} else if (!target.stream().map(s -> s.substring(1, 5)).anyMatch(s -> s.equals(tKey))) {
You don’t need the !sKey.equals(tKey) part of the condition since you are in the else part of the first if statement, so we already know the keys are not equal.
Since we are now doing the substring(1, 5) in three places in the code, you may want to factor it out into a separate method.
It’s an aside, I suggest moving this line:
String sKey = s1.substring(1, 5);
It might as well go between the two for (String lines. No need to take out the substring from s1 once for every s2.

Profanity Test Not Working As Expected (In Chat Application)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to create a profanity test for my app, but it seems to malfunction!! why?
code:
public boolean filter(String message)
{
String[] words={*CUSS WORDS*};
for(int i=0; i< (words.length-1); i++ )
{
if(message.indexOf(words[i].toLowerCase())!= -1)
{
return true;
}
}
return false;
}
OR Another code (BUT SAME FUNCTION):
public boolean filter(String message)
{
String[] words={CUSS WORDS};
for(int i=0; i< (words.length-1); i++ )
{
if(message.contains(words[i}))
{
return true;
}
}
return false;
}
So the PROBLEM IS:
I tried these 2 pieces of codes with similar results. For example for "Fuck", if I enter "fu" into my app it stops it from being entered or for "ass", if I enter "as" it stop it from being entered! (Filter works to stop any profanity from entering the chat)
Store your curse words in a set, then break up the users sentence into individual words. Check each word to see if it's in your set of curse words.
public boolean curse(String str){
//Create your set here
HashSet<String> wordSet = new HashSet<String>();
//Use it's add function to add your curse words
wordSet.add("ass");
String array[] = str.split(" ");
for(String s : array){
if(wordSet.contains(s.toLowerCase()))
return true;
}
return false;
}
I can't comment because of my reputation, but, continuing Elroy Jetson's answer, you initialize the HashSet using Arrays.asList, as is described here in this answer: https://stackoverflow.com/a/16194967/2836264. The HashMap constructor takes in this case a List<String>, that is created from the String[].
String[] cussArray = {"fuck", "shit", "brocolli"};
HashSet<String> cussSet = new HashSet<>(Arrays.asList(cussArray));

If Else Java Syntax Issue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am facing a very basic issue with my logic. Basically I have 2 conditions. One is when !quiet and the other is when its !quiet && _cmdLine.isInteractive.
I have tried to put them in an if else block but with the else I get a syntax error, and if I use just if statements or if-else if, it does not work. I have pasted my code below and need some help. I just cant figure out where I am going wrong on this.
if (!quiet) {
String targetName = getPrintoutNameFromStartable(start,
picoName);
System.out.print("message here");
}
if (_cmdLine.isInteractive()) {
System.out.println("a different message");
return 1;
}
Hope this Helps you understand how to handle two different flags.
if (!quiet) {
String targetName = getPrintoutNameFromStartable(start,
picoName);
System.out.print("message here");
if ( _cmdLine.isInteractive()) {
System.out.println("a different message");
return 1;
}else{
//do something
}
}else{
if ( !_cmdLine.isInteractive()) {
System.out.println("a different message");
return 1;
}else{
//do something
}
}
I think what you are looking for is this:
if (!quiet && _cmdLine.isInteractive()) {
// ...
} else if (!quiet) {
// ...
}

How do I check for an empty string in a Boolean statement? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an assignment where I have to attach the letters "un" to any word that the user inputs (unless the inputted word already has "un" in front of it, in which case I just return the inputted word). I'm testing my method but I encountered one problem: my program keeps returning an error if I were to test for an empty input. Here is my code:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter: ");
String input = keyboard.nextLine();
if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else if(input.equals(""))
{
System.out.println("un");
}
else
{
System.out.println("un" + input);
}
So I wanted to ask how I can test for an empty input/blank string since, evidently, the "" quotations do not work.
There's nothing wrong with checking input.equals("") per-se. The problem is that you have another test beforehand that throws an exception if input is shorter than 2 characters.
There are several ways to solve this, but I'd just simplify things and use startsWith. An empty string doesn't really need a special case of its own - just slap un before it, and you'll get un:
if (input.toLowerCase().startsWith("un")) {
System.out.println(input);
} else {
System.out.println("un" + input);
}
You are having this problem because you are trying to get the substring of string that doesnt have the required length. Put the empty string check first.
if(input.equals("")||input.length==1)
{
System.out.println("un");
}
else if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else
{
System.out.println("un" + input);
}
If this weren't homework, and the library could be used for other things ( using it in this single purpose may be overkill ), you could use StringUtils.PrependIfMissing().
It does exactly this and handles nulls as well.

What is the purpose of the for(... : ...) loop in copying an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
When I go through a tutorial I found this code.. but one place of following code I cannot understand
Can anyone describe what happen from following part
for(String old : oldArray){
System.out.println(old);
}
This is full code....
public class Main {
public static void main(String[] args) {
String[] oldArray = {"one","two"};
String[] newArray = oldArray;
newArray[0]= "three";
for(String old : oldArray){
System.out.println(old);
}
System.out.println("");
for(String latest : oldArray){
System.out.println(latest);
}
}
}
All that this
for(String old : oldArray){
System.out.println(old);
}
does is to loop through the entries of oldArray printing them out one by one. It's equivalent to
for (int i=0; i<oldArray.length; i++) {
System.out.println(oldArray[i]);
}
The code you've put up doesn't do any array copying at all.
This is a for-each loop in Java. It is a short version of iterating over all elements in the array.
What you thus do is iterating over the array and printing each of the elements.
I think in this context it is merely used to validate whether the output is correct.
Ironically enough, the code doesn't perform array copying at all.
public static void main(String[] args) {
String[] oldArray = {"one","two"};
String[] wrongCopy = oldArray;
String[] correctCopy = (String[]) oldArray.clone();
for(String xi : oldArray){
System.out.println(xi);
}
System.out.println("---");
for(String xi : wrongCopy){
System.out.println(xi);
}
System.out.println("---");
for(String xi : correctCopy){
System.out.println(xi);
}
System.out.println("--- after modifications ---");
wrongCopy[0]= "three";
oldArray[1]= "four";
for(String xi : oldArray){
System.out.println(xi);
}
System.out.println("---");
for(String xi : wrongCopy){
System.out.println(xi);
}
System.out.println("---");
for(String xi : correctCopy){
System.out.println(xi);
}
}
jdoodle.
As you can see, if you modify the elements of the oldArray and wrongCopy, they appear on "both" arrays. Whereas the .clone() makes an actual duplicate of the array that is not sensible to modifications from its parent.

Categories

Resources