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);
  }
}
Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
Jesse Cleary
  • 123
  • 1
  • 7
  • 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. – Jon Skeet Jun 04 '15 at 12:29
  • Are you saying that you want to skip the second for loop if it 'breaks' out of your first loop? – almightyGOSU Jun 04 '15 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. – Jesse Cleary Jun 04 '15 at 12:32

7 Answers7

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);
        }
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 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. – Jesse Cleary Jun 04 '15 at 13:02
  • @JesseCleary This is strange. Did you initialize the `isValid` variable to true? – Eran Jun 04 '15 at 13:04
  • 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. – Jesse Cleary Jun 04 '15 at 13:09
  • 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_ Jun 04 '15 at 13:11
  • @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. – Eran Jun 04 '15 at 13:21
  • I believe you are right. As is, it does tell me if there is a negative symbol, but it still prints out all of the chars, whether it is a negative symbol or not. – Jesse Cleary Jun 04 '15 at 13:24
  • @JesseCleary It wouldn't print any character if it detects a `-` symbol. The first loop takes care of that. However, any other char whose int value is smaller than the int value of `'0'` (such as `+`, `,`, `!`, etc...) will be printed. Your first loop should validate that all characters are `>= '0'` and `<= '9'` – Eran Jun 04 '15 at 13:29
  • Gotcha, I think I have it squared away now. I appreciate your (and everyone's) input! Much appreciated! – Jesse Cleary Jun 04 '15 at 13:31
2

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

Phil Anderson
  • 3,146
  • 13
  • 24
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'.

AzNjoE
  • 733
  • 3
  • 9
  • 18
0

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

Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29
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;
    }
}
Mordechai
  • 15,437
  • 2
  • 41
  • 82
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
}
NickJ
  • 9,380
  • 9
  • 51
  • 74
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

FatherMathew
  • 960
  • 12
  • 15