Java Loops - Break? Continue? - java

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);
}
}

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);
}
}
}

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

'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'.

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

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
}

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

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;
}
}

Related

count repeated elements in a string

The question is to find the number of consecutive occurrences of a character '*' in a string.
I've written a program for it but is there any other efficient way to solve this
for(int i=0;i<n;i++){
if(s.charAt(i) == '*'){
count=1;
for(int j=i+1;j<n;j++){
if(s.charAt(j) != s.charAt(i))
break;
else
count++;
}
}
}
For example:
input: *a**b output should be 2
input: ***a**b output should be 3
Simpler a bit, linear complexity (the highest possible effectiveness for this task):
int stars = 0;
int longest = 0;
for(int i=0;i<n;i++){
if(s.charAt(i) == '*') {
stars++;
longest = Math.max(longest, stars);
//here you can do something useful -
// for example, get max number of consecutive stars
}
else {
//here you can do something useful - in case of if (stars > 0)
// for example - increment number of series
//and don't forget to do the same action after loop finish
stars = 0;
}
}

Using return vs While(condition) methods To Break Loops

I'm doing a little google interview question. Find the pair of numbers in a loop that add up to the number given. I found the numbers 2 and 6 that make up 8 so I say match = true so that the while loop stops, however it still proceeds until it finds the second which is 6 and 2 however, those numbers I have already found just the other way around and I had expected my loop to break as my if statement states if there is any 2 numbers that give the sum, match = true therefore terminating the loop, I guess I am wrong though.
However, if I get rid of the while statement and just return; once a match is found it breaks without looking for the second match (which I want it to).
Why is this happening, the logic of both seems the exact same to me.
Using the while(condition) Method
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
boolean match = false;
int sumNeeded = 8;
while(!match){
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j >= 0; j --){
if(list[i] != list[j]){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
match = true;
}
}
}
}
}
}
}
Using return
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
int sumNeeded = 8;
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j >= 0; j --){
if(list[i] != list[j]){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
return;
}
}
}
}
}
}
In your while-loop implementation, if the array doesn't have the desired pair at all it would result in an infinite loop. There is no need for the while statement in your solution.
After you enter into the while loop, you look for all the possible pairs in the array and then check for their sum. If it equals the desired sum, you make the boolean variable match as true.
But, until the nested for loop is completely executed (i.e., all the possible pairs are checked) we do not check for the while condition. The entire nested for loop is executed in one iteration of the while loop. Then, the while loop condition is checked again.
As by the end of the first iteration of the while loop all the possible pairs are accounted for, there is no need for a while loop.
Moreover, there are other logical errors in your implementation. The correct brute-force implementation is as follows:
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
boolean match = false;
int sumNeeded = 8;
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j > i; j --){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
return;
}
}
}
}
}
The inner-for loop is modified to reduce the double-counting of the unordered pairs. Whenever a match is found and printed, we exit the function.
You may also add a break statement inside the while loop in your initial implementation.
if(match == true) {
break;
}
The while condition continues to execute the first and second for-loop until it's finished where as with return it stops execution entirely from the first and second loop.
To fix the while loop you could use a label and then break from that.
firstLoop:
for(int i = 0; i < list.length; i ++) {
match = true;
break firstLoop;

Nested loops/ASCII?

So, for an assignment in my computer science class, we've got to use loops, either for or while, depending on preference. Now, the assignment IS to use said loops and a given input to draw a beauteous ASCII diamond made of '$' and '-'. Say, an input of 5 would look like:
____$
___$-$
__$-$-$
_$-$-$-$
$-$-$-$-$
_$-$-$-$
__$-$-$
___$-$
____$
The underscores are to denote spaces. Now, anytime I try using
public static void main(String[] args) {
String input=JOptionPane.showInputDialog(null, "Input a number between three and ten here: ");
double length=Double.parseDouble(input);
int i=0; int j=0;
for(i=1; i<length; i++)
{
System.out.print(" ");
for(j=1; j<=i; j++)
{
if(j<i){System.out.print("-$");
}
else if(j==i){System.out.println("");}
}
}
I come out with something like, say, for input=7:
-$
-$-$
-$-$-$
-$-$-$-$
-$-$-$-$-$
And yes, the two too few in the center is true with any input. Any help?
Since this is your homework, I'm just going to point you towards the correct answer and leave you to figure out the rest. Let's try formatting your code so you can see what's going on:
public static void main(String[] args) {
String input=JOptionPane.showInputDialog(null, "Input a number between three and ten here: ");
double length=Double.parseDouble(input);
int i=0; int j=0;
for(i=1; i<length; i++){
System.out.print(" ");
for(j=1; j<=i; j++){
if(j<i){
System.out.print("-$");
}
else if(j==i){System.out.println("");
}
}
}
Now, you've got an outer loop for i ranging from 1..length-1, and for each i you're going to print a space, then you're going to count from 1 to 1 and print "-$" that many times. Then, you're going to print a newline and repeat the outer loop, incrementing i
So, the first time through the outer loop, you print one space, followed by one "-$", followed by a newline. Then on the second time through the outer loop, you print one space, followed by "-$" twice, followed by a newline. And so forth, until i=length, and then you stop.
You want to print a few more spaces before you print dollar signs - a loop here will probably be useful.
try to go trough this code and see how it works... it might be useful for your homework
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("input a number");
int number = input.nextInt();
input.close();
boolean add = true;
int counter = 0;
do {
if (add) {
counter++;
print(' ', number - counter);
print('$', counter);
if (counter == number)
add = false;
System.out.println();
} else {
counter--;
if (counter == 0)
break;
print(' ', number - counter);
print('$', counter);
System.out.println();
}
} while (true);
}
private static void print(char c, int times) {
if (c == '$')
times = (times * 2) - 1;
for (int i = 0; i < times; i++)
System.out.print(c);
}
if you edit the print method you will get your desired result
private static void print(char c, int times) {
if (c == '$')
times = (times * 2) - 1;
for (int i = 0; i < times; i++)
if (i % 2 == 1 && c == '$')
System.out.print('-');
else
System.out.print(c);
}

Java Counting letter,digit and symbol

I want to count the number of letter, digit and symbol using JAVA
However the result output is not ideal. it should be 5,2,4
but I got 5,2,13
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
} else if (y.contains("<")) {
symbol++;
}
}
System.out.println(charCount);
System.out.println( digitCount);
System.out.println( symbol);
It should be
} else if (temp == '<')) {
symbol++;
}
In your solution, for every non-letter-or-digit character you check if the entire string contains <. This is always true (at least in your example), so the result you get is the number of special characters in the string.
You should use y.charAt(i) == '<' rather than y.contains("<")
if you use y.contains("<"), it uses the whole string to check whether it contains '<' or not. Since String y contains '<'. When in for loop, there are 4 '<', 6 '+' and 3 '>'.
For checking such charraters, y.contains("<") always be true. That is why you get 13 (=4+6+3) for symbol rather than 4.
This bit is wrong:
y.contains("<")
You are checking the whole string each time when you only want to check a single character (temp)
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
****} else if (temp =="<") {
symbol++;
}
}****
else if (y.contains("<")) {
should be
else if (temp == '<') {
because else every time youu have no letter or digit it is raised.
y.contains("<")
seaches for the substring "<" in the string "apple66<<<<++++++>>>" and it always finds it. This happens 13 times which is the number of chars in the substring <<<<++++++>>>" which does contains neither a letter nor a digt.

Breaking out of For Loop Java

I have this piece of code here:
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
if (input.nextInt() == 999){
break;
} else {
array[i] = input.nextInt();
}
}
I want to break out of the loop if the user enters 999 inside the array but so far no luck. I tried using break or return false but nothing works. Does anyone have a solution? Much thanks!
You are using input.nextInt(); twice.That is reading from console in if and else.
for (int i = 0 ; i < array.length; i++ ) {
int enteredNumber = input.nextInt();
if (enteredNumber == 999){
break;
} else {
array[i] = enteredNumber ;
}
}
You are reading twice inside your loop. So, if your if condition is falsy (user does not enter 999), then it will go into else block where you are reading a new input from user, which can possibly be 999.
Change your loop to:
for (int i = 0 ; i < array.length; i++ ) {
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Apart from that, you should also consider the case where user doesn't actually passes an integer, in which case, your code will blow. You can use Scanner#hasNextInt() method for that.
for (int i = 0 ; i < array.length; i++ ) {
while (!input.hasNextInt()) {
System.out.println("You must pass an integer");
input.next(); // Advance the scanner past the current line.
}
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Of course, that loop might run forever if user keeps on entering non-integer values. To overcome that, you can give user a maximum number of attemps. That I'll leave up to you to handle. (HINT: You will need a counter that goes from 0 to max. On each loop iteration, reset it).
The way you currently have it is that you're calling nextInt() multiple times within each iteration.
That means you'll lose data. Let's say you first enter 7. That's picked up in the if statement as "not 999" so it moves onto the else clause where you ask the user for yet another number (you've lost the 7).
In addition, you'll only break out of that loop if you enter 999 when it's executing the first call to nextInt(). If you enter 999 when it's executing the second call, it will just store it and keep going.
Try this instead:
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
if (next == 999)
break;
array[i] = next;
}
Try this thing in your for loop.
for (int i = 0 ; i < array.length; i++ ) {
int number = input.nextInt();
if (number == 999){
break;
}
System.out.println("aghsdgha" + number);
}
This is the simpler and cleaner way to check the input number.

Categories