Java - For loop (do/while) repeats indefinitely - java

I have been working on a project for my course. It's a simple salary calculator, which I have figured out fairly easily and it functions flawlessly. It also takes into consideration benchmarks for commission. I have completed choped on the last part, however. I cannot get it to function. It either loops indefinitely, or it generates static numbers under the "Total Compensation" column (they should be dynamic based on commission etc).
Bob makes $85,000 a year.
He gets no bonus/commission if he sells less than $120,000
He gets 15% commission if his sales for the year are >= $120,000
He gets an additional 2% for every $150k in sales (150k, 300k, 450k
etc)
User inputs a sales number (example: $300,000).
Program calculates BaseSalary + ($300,000 * .15) + ($300,000 * .02)
Potential Sales on the left and then Total Compensation on the right side
200,000 ----------------------> (Calculated)
220,000 ----------------------> (Calculated)
240,000 ----------------------> (Calculated)
260,000 ----------------------> (Calculated)
280,000 ----------------------> (Calculated)
300,000 ----------------------> (Calculated)
//Variables defined here
double Sales = input.nextDouble();
double TotalCompensation;
int Commission;
double CommissionRate;
double AcceleratedCommissionRate;
int BaseSalary;
double TargetSales;
double Accelerator;
double AcceleratorGoal;
double AcceleratedCommission;
// Mathematical Operations
Accelerator = 0.80;
TargetSales = 150000;
CommissionRate = 0.15;
AcceleratedCommissionRate = ((CommissionRate) * (2.0));
BaseSalary = 85000;
Commission = (int) (Sales * CommissionRate);
AcceleratedCommission = (double) (Sales * AcceleratedCommissionRate);
AcceleratorGoal = (double) 120000;
// If Else Logic Flow
if(Sales < AcceleratorGoal)
{
TotalCompensation = BaseSalary;
System.out.print("\nCommission Goal HAS NOT been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
else if(Sales < TargetSales)
{
TotalCompensation = BaseSalary + Commission;
System.out.print("\nCommission Goal HAS been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
else if(Sales >= TargetSales)
{
TotalCompensation = BaseSalary + AcceleratedCommission;
System.out.print("\nAccelerator Goal HAS been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
// Potential Commission Structure Table
double PotentialSales;
double EndLoop = (Sales * 1.5);
int Increment = 20000;
System.out.println("\nPotential Sales\t\tTotal Compensation");
for (PotentialSales = Sales; PotentialSales < EndLoop;
PotentialSales = PotentialSales += Increment)
{
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(BaseSalary);
System.out.println(output);
}
while(PotentialSales < AcceleratorGoal);
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(Commission + BaseSalary);
System.out.println(output);
}
while(PotentialSales >= AcceleratorGoal && PotentialSales < TargetSales);
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(AcceleratedCommission + BaseSalary);
System.out.println(output);
}
while(PotentialSales >= TargetSales);
}
Any suggestions or tips whatsoever would be a lifesaver.

This code will iterate until expression (PotentialSales < AcceleratorGoal) is false. As you are not updating the value of PotentialSales & AcceleratorGoal in the body of do{..body..}while(expression), it will iterate indefinitely if (PotentialSales < AcceleratorGoal) is true at first place, otherwise it will get executed once and will go to the next statement after the while condition.
Code
do{
String output = numberFormat.format(PotentialSales) + "\t\t" + numberFormat.format(BaseSalary);
System.out.println(output);
}while(PotentialSales < AcceleratorGoal);
You might want to update the PotentialSales or AcceleratorGoal Value inside the body of do while loop or change condition w.r.t output variable.
Same goes for next two do..while loops.

Your do while loop repeats infinitely because,you are not updating the value of PotentialSales in do while loop
To understand the problem,check the following code
int accelerationsales=5;
for(int potentialsales=0;potentialsales<5;potentialsales=potentialsales+=1) {
do {
System.out.println("Hello");
} while(potentialsales<accelerationsales);
}
Run this sample code,you will understand the problem.

Related

How do I add an working if to my code? - Java

I'm building this weird BMI/BMR calculator for school and right now the code does what I want it to do. But I need to add an if (I think) that makes sure that the user doesn't type in values that are too small or too big. The user is only allowed to type in "vikt" between 0.5 and 2.2. If the user types in a faulty value I need the program to execute an else that prints out a "nope you did it wrong".
My problem is that I do not know where to put the if so that the code still works.
So my question is, where and how do I add an if to my code?
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
// Ledtext
System.out.println("Beräkna ditt BMI");
System.out.print("Tryck j för att starta: " );
char fortsätt = input.next().charAt(0);
System.out.println(" ");
do
{
//Användaren matar in sin data
System.out.print("Ange personens vikt (kg): ");
double vikt = input.nextDouble();
System.out.print("Ange personens längd (m): ");
double längd = input.nextDouble();
System.out.print("Ange personens ålder: ");
double ålder = input.nextDouble();
System.out.println(" ");
System.out.println("Beräknat BMI för både män och kvinnor är " + bmi(vikt, längd));
System.out.println("Beräknat BMR för män är: " + kalorier_Män(vikt, längd, ålder));
System.out.println("Beräknat BMR för kvinnor är: "+ kalorier_Kvinnor(vikt, längd, ålder));
System.out.println(" ");
System.out.print("Fortsätta? (j/n): ");
fortsätt = input.next().charAt(0);
}
while (fortsätt != 'n');
}
static double bmi(double vikt, double längd){
double bmiMänochKvinnor;
bmiMänochKvinnor = (1.3 * vikt) / Math.pow(längd, 2.5);
return bmiMänochKvinnor;
}
static double kalorier_Män (double vikt,double längd,double ålder){
double manBmr;
manBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) + 5;
return manBmr;
}
static double kalorier_Kvinnor (double vikt,double längd,double ålder){
double kvinnaBmr;
kvinnaBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) - 161;
return kvinnaBmr;
}
}
From my understanding you want to constrain the values the user can use as an input for this line:
double vikt = input.nextDouble();
You can simply do this by adding an if statement right after that where you check the entered value. If the value doesn't match the condition, you can send a message and continue the loop.
if (vikt < 0.5 || vikt > 2.2) {
// send some message
continue;
}
You can check the values directly after they are read, with an if else statement like this:
if(vikt > 2.2 || vikt < 0.5){
System.out.println("nope you did it wrong");
return; // this will stop the code
}
A better way of handling this problem would be the following function:
private static double retrieveValue(Scanner input, double min, double max, String requestMessage){
while(true){
System.out.println(requestMessage);
double measure = input.nextDouble();
if (measure >= min && measure <= max){
return measure;
} else{
System.out.println("This values is not allowed, please try again:");
}
}
}
You can call it like this:
double vikt = retrieveValue(input, 0.5, 2.2, "Ange personens vikt (kg):");

how can i return and increment in the same for-loop in java

I've encountered the problem where if I increment the for-loop my program crashes after the for-loop has been executed, but if I don't increment the for-loop and use a return statement to return projectedSales my program continues to run.
However, if I don't increase then projectedSales just outputs the last number for projectedSales1 without adding it to projectedSales.
So my question here is, how can i increment the for-loop so that projectedSales = projectedSales + projectedSales1 continues to collect data and returns projectedSales at the end?
Scanner input = new Scanner(System.in);
double projectedRevenue2025 = 0;
double projectedSales1 = 0;
double projectedSales = 0;
double baseSales;
double growthRate;
double numberOfYears;
int [] productPrice = {1825, 670, 880, 1910, 485};
DecimalFormat df = new DecimalFormat("#");
for (double i = 0; i <= 4;) {
System.out.println("What is the base sale?");
baseSales = input.nextDouble();
System.out.println("What is the growth rate?");
growthRate = input.nextDouble();
System.out.println("What is the expected number of years?");
numberOfYears = input.nextDouble();
//calculates the projected sales of the upcoming years
projectedSales1 = baseSales * (Math.pow((1 + (growthRate / 100)), numberOfYears));
System.out.println("The projected sale is: " + df.format(projectedSales1));
//this should store data from projectedSales1 into projectedSales and add it to the previous data
projectedSales = projectedSales + projectedSales1;
projectedRevenue2025 = (projectedSales1 * productPrice[(int) i]) + projectedRevenue2025;
System.out.println("The total projected revenue is: $" + df.format(projectedRevenue2025)); //prints total projected revenue
return projectedSales;
} //close for-loop
input.close();
return projectedSales;
} //closes projSales
PS. the return statement after input.close() is to return projectedSales to the main method
EDIT: I was supposed to hard code this program. My issue was with the input statements in the beginning of the loop. Thank you all, I really appreciate y'all taking the time to help.
I recommend you to use for-loop like this in your case:
for (int i = 0; i < 5; i++) {
// Do your input and previous calculations
projectedRevenue2025 = (projectedSales1 * productPrice[i]) + projectedRevenue2025;
}
I also recommend you to avoid naming variables like var, var1, var2, var2025
Try adding i++ code is like this
for (double i = 0; i <= 4; i++) {
//code goes here
}
if you take out the return statement in the loop and increment the for loop then it should collect data every time and then at the end return the sum of all of the data
Scanner input = new Scanner(System.in);
double projectedRevenue2025 = 0;
double projectedSales1 = 0;
double projectedSales = 0;
double baseSales;
double growthRate;
double numberOfYears;
int [] productPrice = {1825, 670, 880, 1910, 485};
DecimalFormat df = new DecimalFormat("#");
for (double i = 0; i <= 4; i++) {
System.out.println("What is the base sale?");
baseSales = input.nextDouble();
System.out.println("What is the growth rate?");
growthRate = input.nextDouble();
System.out.println("What is the expected number of years?");
numberOfYears = input.nextDouble();
//calculates the projected sales of the upcoming years
projectedSales1 = baseSales * (Math.pow((1 + (growthRate / 100)), numberOfYears));
System.out.println("The projected sale is: " + df.format(projectedSales1));
//this should store data from projectedSales1 into projectedSales and add it to the previous data
projectedSales = projectedSales + projectedSales1;
projectedRevenue2025 = (projectedSales1 * productPrice[(int) i]) + projectedRevenue2025;
System.out.println("The total projected revenue is: $" + df.format(projectedRevenue2025)); //prints total projected revenue
} //close for-loop
input.close();
return projectedSales;
} //closes projSales

confusion about while loop

I'm just starting to learn my first programming language as of yesterday, so I'm writing simple test programs from my java book.
What I'm attempting to do is to have a user enter a static monthly investment and how many months they will be saving for, then display their total savings after that period of time.
when I compile the program it says that in system.out.println at the end of the program that total has not been initialized. I have tried initializing total in just the loop but I figured that would put the scope of it in the loop So I tried initializing it at the top and figured it runs through the loop until the condition is met but doesn't go back to the top of the program to put the value back in so I make another variable at the end of the loop to hold the total at the end of the loop. What's Wrong with my logic
thank you for the help!
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 0){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}
thanks everyone for the help it now compiles however it seems when going through the math it doesn't take in account the first month of savings for example if I do $100 each month its total at the end is %502.08 which I don't believe is right
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount = 0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 1){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
monthCountDown = monthCountDown - 1;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
set totalAmount = 0,that will instialize it, let me know if this fixes the problem
when you declare it declare it like this double totalAmount = 0;
try 2 steps:
double totalAmount; ==> double totalAmount = 0;
while (monthCountDown > 0); ==> while (monthCountDown-- > 0);
Hava a nice day, my friend.
This problem is a little intricate although the compiler (javac program) provides following helpful message:
Compound.java:33: error: variable totalAmount might not have been
initialized double total = totalAmount;
What could be happening you may wonder. The easy answer is to go to line 20 in your program and initialize the value of totalAmount to 0. Then your program would compile.
The reason the compiler does that is rather complicated, but you can reason about it this way:
What if, just what if the while loop did not get run even once (as written, in your program, opposite is happening as you will soon figure out that you are forgetting something about the loop variable)? Then Java would execute the (next) statement double total = totalAmount; and the way this assignment statement is executed is roughly like this:
read the variable on the right side of =, that is totalAmount in a temporary location
transfer the contents of that location to the memory for the variable on the left side of =, i.e. total.
Now, Java does not like to read a local variable's (such as totalAmount) value that is never written to because it may contain some garbage value. When you initialize it with a value like 0, this problem goes away.
First of all there is no need of using intitalAmount and totalAmount. Because each time you are inserting same values to them. Secondly if you make
monthCountdown > 1
then it will count a month less. Because suppose you are counting for 6 months. Now for monthCountdown > 1 the loop will iterate for 5 times and calculate interest for 5 times. Which I believe is not the logic you want to implement.
So it should be,
monthCountdown > 0
Lastly your mathematical logic is not correct because each time you are calculating the interest on the monthly value and adding it with the previous balance. But it should be like each time interest should be calculated on the total current balance.
while (monthCountDown > 0){
totalAmount = ( amountSavedMonthly + totalAmount ) * monthlyInterestRate;
}
Please let me know if any concern.
First of all, it isn't necessarily the case that totalAmount will not be initialized. However, depending on the user input, it is POSSIBLE that totalAmount will not have been initialized, which will then throw an exception when the program attempts to assign the value of totalAmount to total. To avoid this, you need to ensure that totalAmount gets initialized, which is easy to do. When you declare totalAmount, simply assign 0 as its value.
You also have a problem with your while loop. Because the value of monthCountDown is never changed within the loop, there is no way for the condition monthCountDown > 0 to become false. I'm assuming you intended for monthCountDown to be reduced by 1 each time the loop is run, so you should include monthCountDown--; within the loop to prevent it from becoming an infinite loop.
Initialize totalAmount to 0...
Make in while condition greater than 1..
cricket-007 is right about initializing totalamount = 0; But it looks like your while loop keeps going. Try this!
changed your arrow key from > to <, on the while loop
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount =0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown < 0) {
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}

How to show all iterations of a loop, within a single message box?

Everything is working properly, no logic or syntax errors, however, I need the code at the end to display a single message box that shows all iterations at once like a table, as opposed to having x amount of message boxes pop up with results. I'm not sure how to go about it, the only similar examples in my textbook don't use message boxes.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class PenniesForPay
{
public static void main(String[] args)
{
int days;
int maxDays;
double pay = 0.01;
double totalPay; //accumulator
String input;
//Decimal Format Object to format output
DecimalFormat dollar = new DecimalFormat("#,##0.00");
//Get number of days
input = JOptionPane.showInputDialog("How many days did you work?");
maxDays = Integer.parseInt(input);
//Validate days
while (maxDays < 1)
{
input = JOptionPane.showInputDialog("The number of days must be at least one");
days = Integer.parseInt(input);
}
//Set accumulator to 0
totalPay = 0.0;
//Display Table
for (days = 1; days <= maxDays; days++)
{
pay *= 2;
totalPay += pay; //add pay to totalPay
// NEEDS TO SHOW ALL ITERATIONS IN SINGLE MESSAGE BOX
JOptionPane.showMessageDialog(null,"Day " + " Pay" + "\n----------------\n" +
days + " $" + pay + "\n----------------\n" +
"Total Pay For Period: $" + dollar.format(totalPay));
}
//terminate program
System.exit(0);
}
}
You can use a StringBuilder to accumulate all the messages, and then display them, once, after the loop is done:
StringBuilder sb = new StringBuilder();
for (days = 1; days <= maxDays; days++) {
pay *= 2;
totalPay += pay; //add pay to totalPay
sb.append("Day Pay\n----------------\n")
.append(days)
.append(" $")
.append(pay)
.append("\n----------------\n")
.append("Total Pay For Period: $")
.append(dollar.format(totalPay));
}
JOptionPane.showMessageDialog(sb.toString());
Use your JOptionPane.showMessageDialog outside the for loop. Use StringBuffer or StringBuilder to append your messages and show at once.

checkValidity method displays all values as invalid instead of just displaying the invalid values

I have a feeling my issue is somewhere in my if statements in the checkValidity method, but I can't figure out where I went wrong exactly.
Here's the data values used from the file
Sorry if the values look bunched up
DELL: Dell Inc
125 25.567 0.025 28.735 0.025
MSFT: Microsoft
34.1 -15.75 0.012 15.90 0.013
GOOG: Google
56.5 58.125 0.032 67.975 0.030
IBM: IBM Corp
87.3 8.875 0.015 7.500 0.020
DTLK: DataLink
345 23.250 0.055 25.750 0.050
CSCO: Cisco
90 14.570 1.025 16.890 1.024
INTC: Intel
89.1 78.120 0.042 99.355 0.042
BGUS: Bogus Corp
0 25.567 0.012 25.678 0.023
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
public class Profit
{
public static void main(String[] args) throws IOException
{
String input; //string for input from opened file
//Boolean TFStatement; //true/ false statement for validity
int shares = 0; //number of stocks
String company; //name of the company
double sellPrice = 0; //sell price per stock
double buyPrice = 0; //purchase price per stock
double sellTotal = 0; //selling total w/o factoring in commission amount
double buyTotal = 0; //purchase total w/o factoring in buying commission amount
double sellCommissionPercentage = 0; //commission percentage for selling the stock
double buyCommissionPercentage = 0; //commission percentage for buying the stock
double profit = 0; //total profit after buying and selling stocks
double buyCommission = 0; //total purchase commission amount
double sellCommission = 0; //total selling commission amount
DecimalFormat formatPercent = new DecimalFormat("$#,##0.00%"); //format of currency for the profit
//Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get file
System.out.print("Sean Harris\n\n" + "File name: ");
String filename = keyboard.nextLine();
//Open file
File stockFile = new File(filename);
Scanner inputFile = new Scanner(stockFile);
//loop until fils has no more lines to read
while (inputFile.hasNext())
{
company = inputFile.nextLine();
shares = inputFile.nextInt();
buyPrice = inputFile.nextDouble();
buyCommissionPercentage = inputFile.nextDouble();
sellPrice = inputFile.nextDouble();
sellCommissionPercentage = inputFile.nextDouble();
if (checkValidity(company, shares, buyPrice, buyCommissionPercentage, sellPrice, sellCommissionPercentage) == (false))
calcProfit(shares, buyPrice, buyCommissionPercentage, sellPrice, sellCommissionPercentage, profit, buyCommission, sellCommission, sellTotal, buyTotal);
display(company, profit);
}
}
/**
Check if the info in the file is valid
*/
public static boolean checkValidity(String theCompany,int theShares, double theBuyPrice, double theBuyCommissionPercentage, double theSellPrice, double theSellCommissionPercentage)
{
//checking all of the values to see if they are valid
Boolean TFStatement;
TFStatement = (theShares <= 0 || theBuyPrice < 0 || theBuyCommissionPercentage < 0 || theBuyCommissionPercentage > .20 || theSellCommissionPercentage < 0 || theSellCommissionPercentage > .20 || theSellPrice < 0 ? true : false);
/*
if (theShares <= 0 || theBuyPrice < 0 || theBuyCommissionPercentage < 0 || theBuyCommissionPercentage > .20 || theSellCommissionPercentage < 0 || theSellCommissionPercentage > .20 || theSellPrice < 0)
TFStatement = true;
else
TFStatement = false;
*/
//displaying the invalid message if a value is invalid
if (theShares <= 0)
System.out.println(theCompany);
System.out.println("Number of shares invalid: " + theShares);
if (theBuyPrice < 0)
System.out.println(theCompany);
System.out.println("Purchase price invalid: " + theBuyPrice);
if (theBuyCommissionPercentage < 0 || theBuyCommissionPercentage > .20)
System.out.println(theCompany);
System.out.println("Purchase commission percent invalid: " + theBuyCommissionPercentage);
if (theSellPrice < 0)
System.out.println(theCompany);
System.out.println("Sales price invalid: " + theSellPrice);
if (theSellCommissionPercentage < 0 || theSellCommissionPercentage > .20)
System.out.println(theCompany);
System.out.println("Sales commission percent invalid: " +theSellCommissionPercentage);
return TFStatement;
}
/**
Calculate profit
*/
public static double calcProfit(int theShares, double theBuyPrice, double theBuyCommissionPercentage, double theSellPrice, double theSellCommissionPercentage, double theProfit, double theBuyCommission, double theSellCommission, double theSellTotal, double theBuyTotal)
{
//getting the total price of shares sold and bought
//then figure out commission
//then use the four values to calculate profit
theSellTotal = theSellPrice * theShares;
theBuyTotal = theBuyPrice * theShares;
theSellCommission = theSellTotal * theSellCommissionPercentage;
theBuyCommission = theBuyTotal * theBuyCommissionPercentage;
theProfit = (theSellTotal - theSellCommission) - (theBuyTotal + theBuyCommission);
return theProfit;
}
/**
Display company name and profit
*/
public static void display(String theCompany, double theProfit)
{
System.out.println(theCompany);
System.out.println(theProfit);
}
}
Take for example this statement:
//displaying the invalid message if a value is invalid
if (theShares <= 0)
System.out.println(theCompany);
System.out.println("Number of shares invalid: " + theShares);
Perhaps you're coming from a Python background, but in Java, indentation does not indicate nesting. It's merely a readability aid. The only statement that is inside the if is the statement that immediately follows it. In this case: System.out.println(theCompany);.
If you want more than one statement to belong to the same if, they have to be placed in curly braces that makes them a "compound statement":
if (theShares <= 0) {
System.out.println(theCompany);
System.out.println("Number of shares invalid: " + theShares);
}
This applies to all the similar if statements in your code.
Another, unrelated, note:
There is no point in comparing a boolean to false. The equivalent of
if ( checkValidity(...) == (false) ) ...
is simply:
if ( ! checkValidity() ) ...
It's not wrong per se, but it's less readable. Booleans can be used directly in conditions.
For the same reason, an expression like:
condition1 || condition2 || condition3 ? true : false
Is redundant. It's simply equivalent to
condition 1 || condition2 || condition3
Again - it's not wrong, just not readable. A boolean is a boolean.

Categories

Resources