4

I've read through a bunch of threads on using break and continue and I suspect the problem isn't necessarily my use of those, but the layout of my loops. In the following code, I am trying to iterate through the chars in a string that is input by the user to find any - symbols. If found, it will throw an error to the user that a negative number was found and exit. Otherwise, if it does not find a - symbol, it should print out all of the chars in the string.

I used break at the end of my first loop to find the - symbol, but it is not continuing on to the next loop. I tried continue as well but that didn't work. Loops are new to me so I may have this completely wrong, all I know is my first loop is working OK and will throw the error when it finds a - in the string.

strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i = 0; i < strNum1.length(); i++) {
  char c = strNum1.charAt(i);
  if (c == '-') {
    System.out.println("Negative Digit Found - Exiting");
    break;
  }
}

for (int i = 0; i < strNum1.length(); i++) {
  char c = strNum1.charAt(i);
  if (c <= 9) {
    System.out.println(c);
  }
}
3
  • 4
    The first thing to do is fix your formatting. Get your IDE to indent the code appropriately, then make sure your question reflects that. Commented Jun 4, 2015 at 12:29
  • Are you saying that you want to skip the second for loop if it 'breaks' out of your first loop? Commented Jun 4, 2015 at 12:30
  • My intent was to run the first loop, and then if anything checks out and the negative symbol is not found, run the second loop and print all of the chars in the string. Commented Jun 4, 2015 at 12:32

7 Answers 7

3

The break statement breaks you only from the first loop. In order to skip running the second loop in the event of finding a - character, you can use some boolean variable to indicate whether the second loop should run :

strNum1 = JOptionPane.showInputDialog ("Enter Number String");
boolean isValid = true;
for (int i=0; i<strNum1.length(); i++) {
        char c = strNum1.charAt(i);
        if (c == '-'){
            System.out.println("Negative Digit Found - Exiting");
            isValid = false;
            break;
        }
}
if (isValid) {
    for (int i=0; i<strNum1.length(); i++) {
        char c = strNum1.charAt(i);
        if (c <= '9'){
            System.out.println(c);
        }
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

I like this approach. I do notice however that though it will find the negative symbol and present the error message, if there are no negative symbols it does not print the chars in the string. Even if I take out the break; it does not advance to the check for isValid in the second portion.
@JesseCleary This is strange. Did you initialize the isValid variable to true?
I did, I pasted the code exactly as you suggested. In fact, if I comment out the first section and just leave the Boolean isValid = true; and then move immediately to the second section where it checks if (c <= 9) it still doesn't print the chars in the string, which seems odd.
No it's not odd. You probably want to do if (c <= '9') because the numeric value of the character '9' is not 9.
@ci_ Good point. I missed that. Though it's unclear why this (partial) check is necessary at all. If the purpose is to allow only digits, this check should probably be in the first loop and reject the input if it finds a character that is not a digit.
|
2

If you replace the break with a return it will exit the whole method. It sounds like this is probably what you want.

2 Comments

Except there is no sign of a method in the question, so you don't know what else is in it.
Agreed. Hence the "probably"
1

'break;' will stop the loop that it is in from running, where 'continue;' will skip the current 'iteration' in the loop.

 for(int x = 0; x < 10; x++)
 {
     if (x == 5)
        break;
      // other code
 }
 // more other code

This will exit the loop once x == 5, and not do the 6th through 10th iterations.

 for(int x = 0; x < 10; x++)
 {
     if (x == 5)
        break;
      // other code
 }
 // more other code

This will do every iteration, besides the 6th iteration.

But if you want to skip the '// more other code', then you would need to use a 'return;', provided your code is in a function, and it will skip the rest of the function, which in this case is the '// more other code'.

Comments

0

Use the return statement instead of break if you dont want to execcute the second loop after the first one.

Comments

0

You don't say if the number should be an integer, so I'm assuming yes. If so, instead of using loops, a better way of validating the input would be:

int num1;

try {
  num1 = Integer.parseInt(strNum1);
catch (NumberFormatException e) {
  //not a valid number, complain about it
}

if (num1<0) {
  //negative number not allowed, complain about it
}

Comments

0
 for (int i=0; i<strNum1.length(); i++) {
    char c = strNum1.charAt(i);
         if (c == '-'){
            System.out.println("Negative Digit Found - Exiting");
        break;
        }
 }

can be modified as

 if(strNum1.charAt(0) != '-'){
   for (int i=0; i<strNum1.length(); i++) {
    char c = strNum1.charAt(i);
    if (c <= 9){
        System.out.println(c);
    }
   }
 }
else {
 //negative number found...
 }

In This way, unnecessary for loop and break statements can be avoided

Comments

0

All answers are good, but if you want to repeat prompt until you get a valid value, you will need another loop for that, using labels:

negative: while(true) {
    strNum1 = JOptionPane.showInputDialog ("Enter Number String");
    for (int i=0; i<strNum1.length(); i++) {
        char c = strNum1.charAt(i);
        if (c == '-'){
            System.out.println("Negative Digit Found - Exiting");
        continue negative;
        }
    break negative;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.