No break in nested loop? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Working on a task where I should factorize a prime number. Here's the solution I've come up with:
import java.util.Scanner;
public class Task8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Which number to factorize:");
int number = input.nextInt();
System.out.println();
int counter = 1;
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
if (counter == 1 && i == number) {
System.out.println("The number is a prime, can’t be factorized.");
break;
} else {
System.out.println("Prime" + " " + "#" + counter + ":" + " " + i);
number = number/i;
++counter;
}
}
}
}
}
However, a book I'm currently studying, strongly advices against using break statements in loops. So how would I do without one in this case?
Cheers!

Here's one method of doing it. I made comments around my changes:
import java.util.Scanner;
public class Task8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Which number to factorize:");
int number = input.nextInt();
System.out.println();
int counter = 1;
for (int i = 2; i <= number; i++) {
boolean canBeFactored = true; // Add a flag
while (canBeFactored && number % i == 0) { // Add a check
if (counter == 1 && i == number) {
System.out.println("The number is a prime, can’t be factorized.");
canBeFactored = false; // Set that check to false
} else {
System.out.println("Prime" + " " + "#" + counter + ":" + " " + i);
number = number/i;
++counter;
}
}
}
}
}

One possible solution is to do a return in-place of the break. But this will return from the whole function execution, which may not be the desired outcome. Moreover, break statement is not necessarily bad to use. Please refer to this.

I see nothing wrong with using "break" in this case. Although if you would strongly not like to use it, you can make everything you have in main into a new subroutine, and use "return", like this:
import java.util.Scanner;
public class Task8 {
public static void main(String[] args) {
function();
}
public static void function() {
Scanner input = new Scanner(System.in);
System.out.print("Which number to factorize:");
int number = input.nextInt();
System.out.println();
int counter = 1;
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
if (counter == 1 && i == number) {
System.out.println("The number is a prime, can’t be factorized.");
return;
} else {
System.out.println("Prime" + " " + "#" + counter + ":" + " " + i);
number = number/i;
++counter;
}
}
}
return;
}
}

The book probably means that the excessive use of break (and continue, return too) make the code unreadable.
E.g. Instead of
for (int i = 0; i < N; i++) {
if (b)
break;
...
}
You could write
for (int i = 0; i < N && !b; i++) { ... }
In the end I think it's just a matter of style and what you want to express with the code.
You can also break outer loops by labelling them:
outer:
for (;;) {
for(;;) {
if (<some_special_case>)
break outer; // execution...
}
}
// ...continues here
Which can become pretty ugly depending on the scenario without break (additional flag to be set before breaking and checked in all outer loops). So the bottom line is, there are valid use-cases for break where it gets (in my opinion) the job done the cleanest and quickest way (to write the code).

Related

How do i return the value of count from my while loop in Java

I'm new to coding and I'm required to have a return statement but I'm struggling on how to return the values of count from my while loop. I put a link of picture of what I'm getting plus my code is below.
Also I added a printout of "is factor of number " + count just so I can see what count is doing during the while loop. What I really want to do is return these values so when I hit run these values and only these values appear.
Here is my code:
package allFactors;
public class AllFactors {
public static void main(String[] args) {
System.out.println(printFactors(25));
}
public static int printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
System.out.println(count + " is factor of number ");
continue;
}
}
return count;
}
}
my CURRENT output is as follows:
1 is factor of number
5 is factor of number
25 is factor of number
26
i only put system.out.println(count + " is factor of number "); BECAUSE
i want to see what my count value is, NOW i dont want to return count; because that just gives me 26, i want to JUST return 1, 5 and 25. Because these numbers are all factors of 25; once i can do this i will delete my system.out.println(count + " is factor of number "); line of code because it is not necessary. I hope this question make sense
DESIRED OUTPUT
1
5
25
Here you want to return all the factors of the number :
So you can use the list to store all the factors and then return that list and print it, code is this -
package allFactors;
public class AllFactors {
public static void main(String[] args) {
printFactors(32).forEach(System.out::println);
}
public static List<Integer> printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
List<Integer> all_factors = new ArrayList<>();
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
all_factors.add(count);
System.out.println(count + " is factor of number ");
continue;
}
}
return all_factors;
}
}
return is like the output of your function. In the code you said return 0, so no matter what, it will only print 0. Change it to return count; is how you do it.
just return the count from the end of the method as follows
public static int printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
System.out.println(count + " is factor of number ");
continue;
}
}
return count;
}
if you want to return all values you need to use some collection please check below code
package allFactors;
import java.util.ArrayList;
import java.util.List;
public class AllFactors {
public static void main(String[] args) {
System.out.println(printFactors(32));
}
public static List<Integer> printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
List<Integer> factors = new ArrayList<>();
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
factors.add(count);
System.out.println(count + " is factor of number ");
}
}
return factors;
}
}

Suggestions to improve code about primes?

I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}

I need help turing a code with 2 loops into a code with one loop, but has the same output

Right now my code is this
import java.text.*;
import java.util.Scanner;
public class Homework6_EvenOdd
{
public static void main(String[] args)
{
//Varaiable declaration
int even=50;
int odd=51;
//Loop logic for even
System.out.print("Your even numbers are "+even+", ");
while (even <= 99)
{
even += 2;
System.out.print(even + ", " );
}
System.out.println ();
//Loop logic for odd
System.out.print ("Your odd numbers are "+(odd)+", ");
while (odd + 1 <= 99)
{
odd += 2;
System.out.print(odd + ", " );
}
}
}
I can't figure out how to do this with only one loop.
I don't even know where to start. I can't figure out how I would get the even and odd numbers to print on separate lines if there is only one loop?
Here is variant which produces exact copy of your current output:
public class Homework6_EvenOdd {
public static void main(final String[] args) {
final StringBuilder even = new StringBuilder();
final StringBuilder odd = new StringBuilder();
for (int i = 50; i <= 100; i++) {
if ((i & 1) == 0) {
even.append(i + ", ");
} else {
odd.append(i + ", ");
}
}
System.out.println("Your even numbers are " + even.toString());
System.out.println("Your odd numbers are " + odd.toString());
}
}
import java.text.*;
import java.util.Scanner;
public class Homework6_EvenOdd
{
public static void main(String[] args){
//Varaiable declaration
int even=50;
int odd=51;
//Loop logic for even
System.out.print("Your even numbers are "+even+", ");
while (even <= 99 || odd + 1 <= 99){
if (even <= 99) {
even += 2;
System.out.print(even + ", " );
}
System.out.println();
if (odd + 1 <= 99) {
odd += 2;
System.out.print(odd + ", " );
}
}
}
Though I have to say this code is not much better. There are much better ways to figure out if a number is even or odd (hint modulo).
You can collect each of odd and even numbers with List.
After that you can print them.
ArrayList<String> odds = new ArrayList<>();
ArrayList<String> evens = new ArrayList<>();
for (int i = 50; i < 100; i++) {
if (i % 2 == 0) {
evens.add(String.valueOf(i));
} else {
odds.add(String.valueOf(i));
}
}
System.out.println("Your even numbers are: " + String.join(", ", evens));
System.out.println("Your odd numbers are: " + String.join(", ", odds));
Note: String.join() is for Java 8 or later.

How to exit interior loop and go back to main loop in java?

When I run this code, which is a menu with many different options. it consists of many loops. Some of which I have yet to make. But my issue arises when I have the user select "t" or the coin toss simulator. The loop begins but once the user enters the amount of coin flips say 4, it says 2.0 heads and 2.0 tails means 50.0% were heads
Type code letter for your choice: COIN TOSS SIMULATOR
Enter 0 to quit. How many tosses?
It shouldn't say type the letter for your choice: COIN TOSS SIMULATOR, enter 0 to quit. how many tosses?
Also when I enter 0 it says You have entered an invalid option. 't' is not a valid option. I want to Bring back the main menu!!!! what is going on????
public class toolBox {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
boolean properInput = false;
int usersInput;
while (!properInput) {
System.out.println("Enter seed value:");
if (myScanner.hasNextInt()) {
usersInput = myScanner.nextInt();
properInput = true;
Random randomSeed = new Random(usersInput);
String randomNumberList = "";
for (int i = 0; i < 10; i++) {
randomNumberList += randomSeed.nextInt(80) + " ";
}
} else
{
String helloWorld = myScanner.next();
System.out.println("You have not entered an integer. '" + helloWorld + "' is not an integer");
}
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{
Scanner anotherScanner = new Scanner(System.in);
boolean usersSelection = false;
String c;
outer:
while (!usersSelection) {
{
System.out.print("" + "Type code letter for your choice: ");
}
if (anotherScanner.hasNext("q|Q")) {
c = anotherScanner.next();
usersSelection = true;
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
{
System.out.println("" + "COIN TOSS SIMULATOR" + "");
}
System.out.println("Enter 0 to quit. How many tosses?");
Random rand = new Random();
boolean headsOrTails;
float headsCount = 0;
float tailsCount = 0;
Scanner scanMan = new Scanner(System.in);
int numero = scanMan.nextInt();
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
headsOrTails = rand.nextBoolean();
if (headsOrTails == true) {
headsCount++;
} else {
tailsCount++;
}
}
System.out.println(headsCount + " heads and " + tailsCount + " tails means "
+ (headsCount / (headsCount + tailsCount) * 100 + "% were heads"));
}
}
if (anotherScanner.hasNext("g|G")) // if the user were to enter either case of g, the
// program will register both and initialize the
// grade estimator.
{
c = anotherScanner.next();
usersSelection = true;
}
if (anotherScanner.hasNext("c|C"))
{
c = anotherScanner.next();
usersSelection = true;
System.out.println("Welcome to the Color Challenge!");
}
else {
String zoom = anotherScanner.next();
System.out.println("You have entered an invalid option. '" + zoom + "' is not a valid option.");
}
}
}
}
Your question is not clear, but your title suggests to me you think there is an inner and outer loop.
You don't have an inner and an outer loop.
Your indentation was really messy, but when I cleaned it up and then deleted a lot of extra lines of code, the structure of the code became clear.
Notice the following:
1) You have two loops, one on top switched on !properInput, the lower one switched on !usersSelection. There is also a for loop, but it doesn't do anything related to the code flow you are asking about.
2) You have two identical labels, one outside an anonymous block of code (see my comment in the code below), and another inside the anonymous block. In this case it doesn't affect your question, but it is definitely a problem.
My guess is that your break outer line isn't working because you are breaking out of the lower while loop.
I suggest you try fragmenting your code into functions to make the structure clearer.
while (!properInput) {
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{ /* begin anonymous code block */
outer:
while (!usersSelection) {
if (anotherScanner.hasNext("q|Q")) {
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
System.out.println("Enter 0 to quit. How many tosses?");
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
}
}
}
}

All the primes between two parsed user numbers [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
I have a question about a problem. I'm a beginner at this so I appreciate your help!
The code should ask for two user input numbers, and will print out in the console all the prime numbers between these two.
Here is the code I got until now: (It's not checking the numbers between these two, only printing out the one number if it's a prime. )
package questionsAndAnswers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Number {
static boolean primes;
public static boolean number( ) {
try {
for (int i = 0; i < 2; i++) {
BufferedReader br = new BufferedReader(new InputStreamReader System.in));
String num1 = br.readLine();
String num2 = br.readLine();
int number1 = Integer.parseInt(num1);
int number2 = Integer.parseInt(num2);
for (int j = number1; j < number2; j++) {
if ( (j % 2) == 0 ) return true;
for (int k = 3; (k*k) <= j; k+=2) {
if(j % k == 0) {
return false;
}
System.out.println("All the primes b/n number " + number1 + " and number" + number2 + " are :" + j );
return true;
}
System.out.println(primes);
// br.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return primes;
}
}
...and in the main class :
public class TwoWholeNumbers {
public static void main(String[] args) {
System.out.println("Enter two integer numbers to see what is the multitude b/w them: ");
Number.number();
}
}
You have copy pasted code from some place. Issue is you are breaking after first value.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Number {
static boolean primes;
public static boolean number() {
try {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 2; i++) {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String num1 = br.readLine();
String num2 = br.readLine();
int number1 = Integer.parseInt(num1);
int number2 = Integer.parseInt(num2);
for (int j = number1; j < number2; j++) {
if ( (j % 2) == 0 ) {
continue;
}
int x=0;
for (int k = 3; (k*k) <= j; k+=2) {
if(j % k == 0) {
x=1;
break;
}
}
if(x==1) continue;
buffer.append(j + " ");
}
System.out.println("All the primes b/n number "
+ number1 + " and number" + number2 + " are :"
+ buffer.toString() );
}
} catch (IOException e) {
e.printStackTrace();
}
return primes;
}
public static void main(String[] args) {
System.out.println("Enter two integer numbers to see what "
+ "is the multitude b/w them: ");
Number.number();
}
}
My fastest way to check if number is prime:
boolean isPrime(int p) {
int m = (int) Math.sqrt(p);
if(m<2) {
return true;
}else {
for(int i = 2;i++;i<=m) {
if((p % i)==0) {
return false;
}
}
}
return true;
}
You have given return in the number() method instead of break and continue. number() method is not called in a loop in the main() that you need to return for each iteration. Also the boolean return simply doesn't make sense.
I'll show you a few changes you need to do, which will make the program print out a few numbers. But that doesn't mean its the correct output. The logic for prime numbers is highly faulty. You'll have to fix that. I'm just helping you solve the basic problem of why you don't get any output.
for (int j = number1; j < number2; j++) {
if ((j % 2) == 0)
continue; // return true replaced by continue
for (int k = 3; (k * k) <= j; k += 2) {
if (j % k == 0) {
break; // return false replaced by break
}
System.out.println("All the primes b/n number "
+ number1 + " and number" + number2 + " are :"
+ j);
}
}
I've given the break and continue to avoid return statements, but in reality, the logic really needs a makeover.

Categories

Resources