So my professor mentioned that a break in an if/if-else statement is "bad" code.
What exactly does she mean by that? Also how am I able to fix my code that I currently have written, because it does work the way I want it to, it's just now I need to get ride of the break statement.
int sumOne = 1;
int sumTwo = 1;
int sumOneTotal = 0;
int sumTwoTotal = 0;
while(sumOne > 0 || sumTwo > 0){
System.out.print("Enter a number to add to first sum: ");
//The user enters in a value for the first sum.
sumOne = input.nextInt();
/**
* We use an if-else statment to ensure sumOne is never less than or equal to 0.
* If it does it ends the program immediately and totals the sums.
* This is because we only want the user to enter in positive numbers.
*/
if (sumOne <= 0){
break;
}else{
sumOneTotal = sumOneTotal + sumOne;
}
System.out.print("Enter a number to add to second sum: ");
//The user enters in a value for the second sum.
sumTwo = input.nextInt();
/**
* We use an if-else statment to ensure sumTwo is never less than or equal to 0.
* If it does it ends the program immediately and totals the sums.
* This is because we only want the user to enter in positive numbers.
*/
if (sumTwo <= 0){
break;
}else{
sumTwoTotal = sumTwoTotal + sumTwo;
}
}
//We print out the total of sumOneTotal and sumTwoTotal.
System.out.printf("%1s%1d%12s%1s%1d", "First sum: ", sumOneTotal, " ", "Second sum: ", sumTwoTotal);
Essentially I want the user to enter ANY positive number and that number is added to the first or second sum. Once the user enters any number <= 0 I want the program to stop immediately. The issue that I keep having when I tinker with the code is that the code keeps running through. Meaning if I have the user enter in 0 to be added to the first sum, the code still asks the user to enter in a number for the second sum. I need it to stop right away and not continue. Any help would be a great help! I am using Java.
EDIT!!! So let's say hypothetically I want to make a program that does the exact same thing I am doing now just with no break statement. How would I do so? A few rules. The most outer statement must be a "while" loop. The inner workings of it can be anything. I also need the machine to print out "Enter a number to add to first sum:" and "Enter a number to add to second sum:" alternating. So if I entered in 1,2,3,4. The first sum would be 4 and the second sum would be 6. Last rule is that it can not contain any break statements!
This is a throwback to when structured programming was a new thing, back when goto statements and the like were everywhere. In theory, Ideally, you should never have to use breaks/continues, and only have a single point of return. In reality, doing so can make your job a lot harder by making programs harder to write, harder to read, and take up more computing resources. Multiple returns, continues and breaks are middle men between truly structured programming and spaghetti code. Used properly, there is nothing wrong with them.
Generally, I've found that they will only obscure your code if you're already using bad practices that make your code hard to read (For example, writing huge blocks of logic without breaking it up, tightly coupling objects etc).
If you're interested, here is a link to an interesting perspective on why NOT to use them. And here is a perspective on why they are benefical.
Many others have already answered with code, but here is my shot :)
public class Main {
public static void main(String args[]) {
int sumOne = 1;
int sumTwo = 1;
int sumOneTotal = 0;
int sumTwoTotal = 0;
Scanner input = new Scanner(System.in);
while(sumOne > 0 || sumTwo > 0){
System.out.print("Enter a number to add to first sum: ");
sumOne = input.nextInt();
if (is_positive(sumOne)){
sumOneTotal = sum_numbers(sumOneTotal, sumOne);
System.out.print("Enter a number to add to second sum: ");
sumTwo = input.nextInt();
if(is_positive(sumTwo)){
sumTwoTotal = sum_numbers(sumTwoTotal, sumTwo);
}
}
}
System.out.printf("%1s%1d%12s%1s%1d", "First sum: ", sumOneTotal, " ", "Second sum: ", sumTwoTotal);
return;
}
public static int sum_numbers(int x, int y){
int total = x + y;
return total;
}
public static boolean is_positive(int x){
boolean is_pos = true;
if(x < 0){
is_pos = false;
}
return is_pos;
}
}
I'd say it's now harder to read. The more to the right my code starts to gravitate, the more I feel sorry for who needs to maintain it.. of course, I could remove a level or two of indentation by wrapping (more) bits in methods. Then it becomes easier to read, but there's a point where black-boxing every tiny bit of logic just seems redundant...
If you draw the flowchart of your code you can see it exits a bucle in the middle of it, which isn't right, the right way is for it to exit when evaluated on the while, also when someone is reading your code they should expect the bucle is left when evaluated false on the while not in a random if inside the while block, I took your code and made some fixes to make it work as expected but I'm not sure if that's what your teacher expects.
int sumOne = 1;
int sumTwo = 1;
int sumOneTotal = 0;
int sumTwoTotal = 0;
while (sumOne > 0 && sumTwo > 0) {
System.out.print("Enter a number to add to first sum: ");
// The user enters in a value for the first sum.
sumOne = input.nextInt();
/**
* We use an if-else statment to ensure sumOne is never less than or
* equal to 0. If it does it ends the program immediately and totals
* the sums. This is because we only want the user to enter in
* positive numbers.
*/
if (sumOne > 0) {
sumOneTotal = sumOneTotal + sumOne;
System.out.print("Enter a number to add to second sum: ");
// The user enters in a value for the second sum.
sumTwo = input.nextInt();
/**
* We use an if-else statment to ensure sumTwo is never less
* than or equal to 0. If it does it ends the program
* immediately and totals the sums. This is because we only want
* the user to enter in positive numbers.
*/
if (sumTwo > 0) {
sumTwoTotal = sumTwoTotal + sumTwo;
}
}
}
Much cleaner, no breaks.
int candidate = 0;
int [] sums = {0,0};
int index = 1;
System.out.print("Enter a number to add to first sum: ");
while((candidate = input.nextInt()) > 0){
sums[index] = sums[index] + candidate;
index = (index + 1)%2;
System.out.print("Enter a number to add to " + ((index == 0) ? "first":"second" ) + " sum: ");
}
//We print out the totals.
System.out.printf("%1s%1d%12s%1s%1d", "First sum: ", sums[0], " ", "Second sum: ", sums[1]);
That isn't to say you should always avoid breaks, but in this case you can avoid it to make your code shorter, less redundant.
Sometimes avoiding break is worse than using it. I would write it like this with one less break.
int sumOneTotal = 0;
int sumTwoTotal = 0;
while (true) {
System.out.print("Enter a number to add to first sum: ");
//The user enters in a value for the first sum.
int sumOne = input.nextInt();
if (sumOne <= 0)
break;
sumOneTotal += sumOne;
System.out.print("Enter a number to add to second sum: ");
//The user enters in a value for the second sum.
int sumTwo = input.nextInt();
if (sumTwo <= 0)
break;
sumTwoTotal += sumTwo;
}
You can avoid break but this doesn't make the code clearer/simpler IMHO.
int sumOneTotal = 0;
int sumTwoTotal = 0;
boolean okay = true;
do {
System.out.print("Enter a number to add to first sum: ");
//The user enters in a value for the first sum.
int sumOne = input.nextInt();
if (sumOne <= 0) {
okay = false;
} else {
sumOneTotal += sumOne;
System.out.print("Enter a number to add to second sum: ");
//The user enters in a value for the second sum.
int sumTwo = input.nextInt();
if (sumTwo <= 0) {
okay = false;
} else {
sumTwoTotal += sumTwo;
}
} while (okay);
The same advice applies to using labels. Avoid them where possible unless avoiding them means doing something worse.
while (sumOne > 0 && sumTwo > 0) {
System.out.print("Enter a number to add to first sum: ");
sumOne = input.nextInt();
if (sumOne > 0) {
sumOneTotal = sumOneTotal + sumOne;
System.out.print("Enter a number to add to second sum: ");
sumTwo = input.nextInt();
if (sumTwo > 0)
sumTwoTotal = sumTwoTotal + sumTwo;
}
}
but i agree with others - there is no any sense to avoid "break"
I don't necissarially agree that it is always bad practice to use a break inside an if. However, that is more a matter of opinion than anything, and is not really on topic here. I will answer the part of your question that is on topic, namely: how can I fix my code to not use break inside an if.
The code below will continue to loop, asking a user for input, until they input a valid number. This avoids your original problem and has the added benefit of allowing the user a chance to enter a new number if they make a mistake, instead of exiting the loop and making them start over.
int sumOne = 1;
int sumTwo = 1;
int sumOneTotal = 0;
int sumTwoTotal = 0;
while(sumOne > 0 || sumTwo > 0){
do {
System.out.print("Enter a number to add to first sum: ");
//The user enters in a value for the first sum.
sumOne = input.nextInt();
System.out.print("Enter a number to add to second sum: ");
//The user enters in a value for the second sum.
sumTwo = input.nextInt();
}while(sumTwo <= 0 || sumOne <= 0);
sumOneTotal = sumOneTotal + sumOne;
sumTwoTotal = sumTwoTotal + sumTwo;
}
//We print out the total of sumOneTotal and sumTwoTotal.
System.out.printf("%1s%1d%12s%1s%1d", "First sum: ", sumOneTotal, " ", "Second sum: ", sumTwoTotal);
Related
I am very new to java and I need help. Basically, I have a program that asks the user to input a number. When the number is input, it takes a sum of all of the odd numbers before that number and adds them up. What I'm trying (and failing) to do is, make another loop whereby, when the user is prompted to ask for a number to sum up the odd numbers, I want to make it so that it will only continue when an odd number is entered, otherwise it will keep repeatedly asking the user until they enter an odd number. I know that using a while loop will solve this issue, but I'm not sure how to get it to work.
Here's my code:
import java.util.Scanner;
public class OddCalculator {
private static Scanner sc;
public static void main(String[] args)
{
int number, i, oddSum = 0;
sc = new Scanner(System.in);
System.out.print(" Please Enter any Number : ");
number = sc.nextInt();
while (number % 2 !=0) //HERE IS WHERE IM HAVING THE ISSUE
{
continue;
}
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\n The Sum of Odd Numbers upto " + number + " = " + oddSum);
}
}
Thanks in advance!
continue; as a statement scans 'upwards and outwards' for the first construct that can be continued. Things that can be continued are currently only for, while and do/while statements, so it finds while (number % 2 != 0) and will continue it.
To continue a while loop means: Jump straight back to the condition number %2 != 0, evaluate it, and then enter the loop again if it is true, or hop to the } if it is false.
So, your code checks if the number is odd. If it is, it will .. continue. So, it will.. check if the number is odd. If it is, it will check if the number is odd. If it is, it will check if the number is odd.... forever.
Presumably your intent is to ask the user again, but then you'd have to wrap the loop around more code: Start with the print, because certainly sc.nextInt() needs to be inside the loop. That does mean you won't have a number value to check, but that's what do/while loops are for: To guarantee you loop at least once (and so that you can use anything calculated in the loop as part of the condition).
You should also use the scanner inside the while loop in case the number is not odd.
while (number % 2 !=0) {
number = sc.nextInt(); // Use here as well to keep asking for a number until is odd
}
Your confusion seems to be coming from misunderstanding that continue means going back to the while loop, and break is what gets you out of the loop. Does this work for you?
System.out.println(" Please Enter any Number : ");
number = sc.nextInt();
// keep asking for a number for as long as it is even (condition is false on odd)
while (number % 2 == 0) {
System.out.println("Please enter another number: ");
number = sc.nextInt();
}
System.out.println(number + " is now odd!");
I hope this output is what you are looking for, the reason why your previous code doesn't work is that number = sc.nextInt(); is the reason why you can prompt the user for an input, so you have to loop it, furthermore, you can give a specific prompt base on what the user has inputted in the if statement, hope this helps!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// int number, i, oddSum = 0;
int number, i, oddSum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter any Number : ");
do{
number = sc.nextInt();
if(number % 2 == 0){
System.out.print("Please Enter an odd number!: ");
}
}while(number % 2 == 0);
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\nThe Sum of Odd Numbers up to " + number + " = " + oddSum);
}
}
Output:
Please Enter any Number : 2
Please Enter an odd number!: 2
Please Enter an odd number!: 3
The Sum of Odd Numbers up to 3 = 4
My programs asks the user to input integers (on a loop) until they input -99; which will then display the highest and lowest numbers of the input integers. I have a variable called count, that increments every time the user puts in a new integer, to keep track of the number of integers inputted by the user. How can I have -99 not included as one of the integers and not incrementing count?
Code:
//variables
int num = 0, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
low = num;
high = num;
//loop
while(num != -99){
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++;
if (num == -99 && count == 0)
{
count--;
System.out.println("You did not enter a number");
} //outer if end
else {
//higher or lower
if(count > 0 && num > high)
{
high = num;
} //inner else end
else if(count > 0 && num < low)
{
low = num;
} //inner else if end
else
{
} //inner else end
} //outer else end
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
You approach is good, but you missed some points,
your condition to find max or min is also wrong because you have to write them separately.
User Entered any value or not, you have to decide this outside the loop.
You have to initialize high and low with first input.
I am trying to make some correction in your program, just changing the required part. Hope it will help you.
//variables
int num = 0, count = 0, high =0 , low = 0;
Scanner userInput = new Scanner(System.in);
//loop
while(true){
//Using infinite loop, we will break this as per condition.
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
if(num == -99)
{
break;
}
count++;
if(count == 1)
{//initialize high and low by first number then update
high = num;
low = num;
}
//to check highest
if(num > high)
{
high = num;
}
//to check smallest
if(num < low)
{
low = num;
}
}
if (count == 0)
{//Here we check that if user enter any number or directly entered -99
System.out.println("You did not enter a number");
}
else
{
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
}
I would recommended the following solution :
First of all, get a number from the user before the loop.
Then check if the number is -99 or not.
You know what to do if it is.
If not, start a do-while loop and do the following :
Increment the count.
Update your low and high.
And the last statement of the loop body will get another number from the user.
The while condition after the loop body will check that the latest number entered is not -99.
I think I have to use String goAgainResponse to make there not be an infinite loop but I don't know what the code for that would look like. I'm supposed to approximate pi by adding 4 - 4/3 + 4/5 - 4/7 + 4/9 etc. adding as many of these terms together as the number that I ask the user to put in.
int term;
int counter = 1;
double piCalc=0.0;
String goAgainResponse = null;
boolean goAgain = false;
Scanner kb = new Scanner(System.in);
/* NOTE you may not declare any additional variables */
do
{
System.out.println("This program will approximate Pi based on the following series:");
System.out.println("4 - 4/3 + 4/5 - 4/7 + 4/9 - ...");
System.out.println("Enter the term number to which you would like to approximate Pi");
term = kb.nextInt();
while(term <= 9)
{
System.out.print("Please enter a number greater than 9:");
term = kb.nextInt();
}
while(term > 9)
{
term += 1;
piCalc = 4/(2 * term - 1);
System.out.print(piCalc);
}
System.out.print("Would you like to try again (yes/no)? ");
}while(goAgain);
while(term <= 9)
{
System.out.print("Please enter a number greater than 9:");
term = kb.nextInt();
}
In this you are saying term should be greater than 9. But your in your second loop condition is term>9 and you are adding values in term, thats why the second loop is infinte
while(term > 9)
{
term += 1;
piCalc = 4/(2 * term - 1);
System.out.print(piCalc);
}
changing the condition of 2nd loop would resolve your problem. OR
consider term+=1 again.
Also as per #Scary Wombat, value of boolean doagain is never set
boolean goAgain = false;
This is never set to anything else, and the loop only loops while it is true
System.out.print("Please enter the max number:");
int max = input.nextInt();
System.out.print("Please enter the base:");
int base = input.nextInt();
for (int i = 0; i <= max; max % base == 0;) {
System.out.println("Number is " + i);
}
How do I get it to print the multiples of a number?
Although Diabolus already has a solution, here's the same using a for loop:
for(int i = base; i <= max; i++)
{
if(i % base == 0)
System.out.println("Number is - " + i);
}
The number iterates from the base to the maximum number (if you start from zero, 0 too will be printed, as it divides completely by any number)
Note that even the base number will be printed. If you wish to avoid this, set i = base to i = base + 1.
I'm not sure if I have fully understood your question. However, I believe this is the solution you were looking for:
int currentMultiple = 0;
int step = 1;
do {
currentMultiple = (base * step);
System.out.println(currentMultiple);
step += 1;
} while ( currentMultiple <= max );
You're needing a while or do while loop for this problem. Since you are unaware of when the current multiple is going to exceed the input.
Let me know if this is what you needed!
I have a for-loop which asks for scores between 0 and 10. It asks a certain amount depending on the number of judges.
Here's the code:
System.out.println("Number of judges: ");
int numOfJudges = IO.readInt();
int sum = 0;
for (int i=0; i<numOfJudges; i++) {
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
} else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
System.out.println(sum);
I want to make is so if a number is entered that's not between 0 and 10, it won't count that as one of the conditions as i < numOfJudges.
For example if I have 3 judges and I enter 2 wrong inputs, it will still only run the loop 3 times (and only take the good input into account) while I really want it to run 5 times to make up for the two incorrect inputs.
Increment numOfJudges in case of ELSE condition so that your FOR loop would run until you have desired number of correct inputs.
This is shortest and cleanest solution.
else {
System.out.println("Incorrect number, must be between 0 and 10.");
numOfJudges++;
}
You can use a while loop inside of the for-loop, instead of adjusting the for-loop:
for (int i=0; i<numOfJudges; i++) {
while(true){
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
break; //jump out of while-loop
}else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
}
System.out.println(sum);