Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Loops - Break? Continue?

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);
  }
}
like image 884
Jesse Cleary Avatar asked Oct 12 '25 09:10

Jesse Cleary


2 Answers

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);
        }
    }
}
like image 106
Eran Avatar answered Oct 14 '25 22:10

Eran


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

like image 41
Phil Anderson Avatar answered Oct 14 '25 23:10

Phil Anderson