I am a new coder. Working on an assignment. This is also my first post here so I apologize if it's a little sloppy.
I'm having some troubles with my if/else statements in Java...the "if" conditions seem to work okay. But my "else" conditions do not. Take a look at the code and the build results below.
Basically, I enter an ingredient. And then I put in the number of cups needed. And the number of calories the ingredient has per x cup. That all seems to work as long as I input what I want to for "successful" results.
Successful Build Image
But when I start to input values outside of my criteria, my application doesn't seem to care. If I input 0, I should get that output of "your response is invalid" or whatever it is I coded. But it just seems to skip over that entirely.
Bad Code Image
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 || numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Problem was in line:
if (numberCups >= 1 || numberCups <= 100) {
...
}
When you entered 0, program checked if 0 is greater or equal to 1, and that was false but you had also "or" condition ( || ), and in that condition you were checking if 0 <= 100 and because that is true, false || true gives true and that's why your if statement was correct. You needed to use "and" ( && ) instead of "or". There was flaw in your logic.
Test code below, it should work now:
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 && numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Just to clarify. The following statement
if(numberCups >= 1 || numberCups <= 100) {
...
}
Is true any number of cups. Any number of cups >= 1 will be caught by the first condition. Any number of cups <= 0 will be caught by the second condition since in that case they will all be less than 100. With a logical || only one condition is required to be true for the statement to be true.
In fact,
if(numberOfCups is >= A || numberOfCups <= B) {
...
}
will always be true as long as B >= A-1.
Related
My program should execute these steps:
Generate random no from 0 to 100.
Display random no and ask user enter (h/l/c)? (user have to enter one of them).
If it is correct ask user if they like to play again (y/n)? (user must answer (y/n))
I was able to execute Question no.1. Question no.2, random no display but I am unable to type character (h/l/c). Also, I am not able to ask player if they want to play again or not?
Here is what I have done:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number;
int guess = 0;
int min = 0;
int max = 100;
int answer= (min+max);
number = (int) (Math.random() *100 +1);
System.out.println("Guess a number between 1 and 100.");
//Ask user to type higher 'h', lower 'l' and correct 'c'.
System.out.println("Is it " + number + " ?" + " (h/l/c): " );
//
guess = 50;
while (guess <= 7)
{
System.out.println( "It is: " + guess + "?" + "(h/l/c) : " );
//Type 'h' if guess is high, 'l' for low and 'c' for correct.
if(answer == 'h')
{
max = guess -1;
min = 0;
guess = ((max = min)/2) + min;
guess++;
} else if (answer == 'l')
{
max = 100;
min = guess + 1;
guess = ((max+min)/2);
guess++;
} else if (answer == 'c');
}
System.out.println("Great! Do you want to play again? (y/n): ");
if(answer == 'y')
{
System.out.println("Guess a number between 1 and 100.");
//else prompt another question with if else
} else{
System.exit(0);
}
}
}
Your program does not accept any user input about if the guess is too low or too high.
You declared "answer" with an equation so it should accept a number.
answer would require a char or String value.
answer = keyboard.nextChar(); //read a char
answer = keyboard.nextLine(); //read a String
The idea is to create an average for money made in a week by day and my average must be calculated in a method that is called in the main method. That is the easy part, but the part I'm stuck on is if a number less than zero is entered it should give me an error message and re-prompt the user for a better value. I'm not looking for a handout here just for someone to tell me what I've been doing wrong if it is simple and easy or a pointer in the right direction.
import java.util.*;
public class weeklyAveragesClient2
{
public static void main(String [] args)//output averages in format
{
averageCash();
}
public static double averageCash()//use array and loop to calculate weekly average
{
double [] cashMoney;
cashMoney = new double[7];
Scanner scan = new Scanner(System.in);
int j = 0;
String s = "ERROR";
while (j < 7)
{
double num = cashMoney[j];
if (num == 0)
{
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
}
else if(num > 0)
{
System.out.print("Please enter an amount for day " + (j+1) +": ");
cashMoney[j] = scan.nextDouble();
j++;
}
else
{
System.out.println("Error: negative number please enter a number > 0");
}
}
System.out.println("Calculating...");
double sum = 0;
for (int i = 0; i < cashMoney.length; i++)
{
sum = sum + cashMoney[i];
}
double average = sum / (double)cashMoney.length;
System.out.println("Average: " + average);
return average;
}//end averageCash
}//end class
I've added some comments that will hopefully provide food for thought.
// This will *always* be zero at first because you haven't called scan.nextDouble() yet
// and zero is the default value. So when you run the program, it will output "Error
// please enter a number > 0" before doing anything else
if (num == 0) {
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
} else if (num > 0) {
System.out.print("Please enter an amount for day " + (j + 1) + ": ");
cashMoney[j] = scan.nextDouble();
j++;
} else {
// If we get into this state, the user will never be invited to enter
// another number, since the last entered number was negative, so
// num == 0 is false, and
// num > 0 is false, so
// we'll end up back here. In fact, you'll enter an infinite loop and
// this message will be printed over and over again.
System.out.println("Error: negative number please enter a number > 0");
// cashMoney[j] = scan.nextDouble(); // <-- try prompting the user again
}
Please also consider indenting your code correctly. It will greatly increase readability. If you're using an IDE like Eclipse, you can select Source > Format.
//Setting my variables.
Scanner keyboard = new Scanner(System.in); // Initalizing keyboard to scanner input
int quarter;
double balance, intrestRate;
boolean correct = false;
//Loop iterations to resolve error, and determine value for each input.
do{ //Beginning loop for number of quarters, must be between 1-10
System.out.println("Enter a number between 1 and 10 for the amount of quarters");
quarter = keyboard.nextInt();
if(quarter >= 1 && quarter <= 10) //If quarter is between 1 and 10
{
System.out.println("You have " + quarter + " quarters.");
correct = true;
}
else
{
System.out.println("Number of quarters must be between 1 and 10");
correct = false;
}
}while(!correct);
do{ //Second loop for rate of intrest.
System.out.println("Enter intrest rate without percent a sign. Must be greaters than 5% and less than 25%.");
intrestRate = keyboard.nextDouble();
if (intrestRate >= 5 && intrestRate <=25)
{
System.out.println("You have selected a " + intrestRate + "% rate of intrest.");
correct = true;
}
else
{
correct = false;
}
}while(!correct);
}
}
So, this is my code. I'm experimenting with loops, and if-else type statements. I feel like, MY approach is way to complicated and could be easily summarized or revised period. Does anyone know how to approach with, with only declaring one do statement? This code is just in the beginning phases of my experiment and has much work to do. But before I move on, I was hoping for another set of eyes!
Use of infinite loop with break on valid input. Enhanced to handle bad input.
Scanner keyboard = new Scanner(System.in);
int quarter;
while (true) {
System.out.print("Enter number of quarters (1-10): ");
if (keyboard.hasNextInt() && (quarter = keyboard.nextInt()) >= 1 && quarter <= 10)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Number of quarters must be between 1 and 10");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have " + quarter + " quarters.");
double intrestRate;
while (true) {
System.out.print("Enter interest rate (5%-25%), without percent sign: ");
if (keyboard.hasNextDouble() && (intrestRate = keyboard.nextDouble()) >= 5 && intrestRate <= 25)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Interest rate must be between 5% and 25%");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have selected a " + intrestRate + "% rate of interest.");
After three invalid entries I need the 3rd time to display something different and revert back to the first loop. Also am not sure how to make this continuous
do{
System.out.print("Enter Rating(-1 to quit): ");
rating = input.nextInt();
}
while (rating == 0 || rating == 1 || rating == 2 || rating == 3 || rating == 4);
System.out.print("Invalid entry. Please enter a whole number "
+ "or enter -1 to quit: ");
rating = input.nextInt();
You can use while (rating < 0 || rating > 4)
Do you mean this?
/**
<P>{#code java Test}</P>
**/
public class Test {
public static final void main(String[] ignored) {
int iterationCount = 5;
for(int i = 0; i < iterationCount; i++) {
if(i == 2) { //Index of 3 is 2
System.out.println("Printing something special on the third iteration!");
//You could set i back to 0 here, if that's what you want...
} else {
System.out.println("Index " + i);
}
}
}
}
Output:
[C:\java_code\]java Test
Index 0
Index 1
Printing something special on the third iteration!
Index 3
Index 4
I am trying to validate the the user input, but I can't get it to work.
The user has to enter an amount of Revenue between 0-20,000, but not anything more than that.
In addition, the user must enter expenses between 1500-10000, but not anything more than that or less than that.
I also am trying to loop the code as well. I am asking the user if they have additional records they want to enter in or not, and I am counting how many times the record has been done.
Can anyone tell me what I am doing wrong and point me in the right direction?
Here is what I have so far:
import javax.swing.JOptionPane;
import java.io.*; // Access System.out
import java.util.Scanner;
public class RevenueScan
{
public static void main(String[] args)
{
// Declarations
Scanner in = new Scanner(System.in);
int productNumber;
float revenue;
float expenses;
double finalValue;
char repeat;
int counter = 0;
String input;
Scanner keyboard = new Scanner(System.in);
// Do Loop to run
do
{
// Pop up to advise the user the conditions that have to be met for inputs
System.out.println("Please ensure that your revenue is between 0 to 20,000.00 dollars."
+ "\nPlease ensure that your expenses are between 1,500.000 to 10,000.00 dollars.");
// Pop up to ask the user the values of the variables
System.out.println("Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
// Read in values
productNumber = in.nextInt();
revenue = in.nextFloat();
expenses = in.nextFloat();
//States the values entered by user
while (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000);
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
//calculates final value
}
}
finalValue = revenue - expenses;
// Calculates final value and displays as net profit, loss or break even.
if (finalValue > 0)
{
System.out.println("You made a profit. Your net income is: " + finalValue);
}
else
if (finalValue == 0)
{
System.out.println("You broke even. Your revenue was " + revenue + " your expenses were " + expenses);
}
else
if (finalValue < 0)
{
System.out.println("You have not made any profit. Your net loss is: " + finalValue);
}
System.out.println("Number of records: " + counter);
//validate user input
System.out.println("Would you like to input more records?");
System.out.println("Enter 'Y' for yes or 'N' for no.");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
while (repeat == 'Y' || repeat == 'y');
{
}
}
}
You have a ; after the while-statement, it shouldn't be there, otherwise the while-loop is empty, as opposed to containing the block following it.
while (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000)
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
}
}
But once you fix this, the above block will just keep looping, since none of the values can change inside that loop.
Also, those inner brackets {} are somewhat pointless.
I recommend this:
if (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000)
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
continue; // go to the start of the do-while loop
}
Then you also have to change:
char repeat;
to:
char repeat = 'Y';
otherwise it doesn't compile since continue still triggers the condition check, and repeat won't be initialized the first time, and Java doesn't allow this.
If you want to stick to a while-loop, put something like these lines in there:
// tell user to input values again
System.out.println("Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
// read in values
productNumber = in.nextInt();
revenue = in.nextFloat();
expenses = in.nextFloat();
This will allow the user to input new values until the conditions are met.
And the format of a do-while loop is:
do { ... }
while (...);
Not:
do { ... }
while (...) { ... }
So change:
while (repeat == 'Y' || repeat == 'y');
{
}
To:
while (repeat == 'Y' || repeat == 'y');