Question

Java Branches code not working please HELP!! I am trying to build this class that will...

Java Branches code not working please HELP!!

I am trying to build this class that will ask for an ingredient, and the number of cups of the ingredient. It should then branch into an if/else branch off to verify that the number entered is valid and that it is within range. Once that branch completes it should then continue on to ask for the calories per cup, and then calculate total calories. Once I get it to enter the branch though I get a compile error and the program terminates. I am not sure how to nest the branch in with the rest of the code I guess. Thank you in advance to anyone that can help me out with this!

The code is below:

package ingedientclass;

import java.util.Scanner;

/**
*
* @author
*/

public class IngedientClass {

  
public static void main(String[] args) {
String nameOfIngredient = "";
double numCups = 0;
int numCaloriesPerCup = 0;
double totalCalories = 0.0;
final int MAX_CUPS = 100;

Scanner scnr = new Scanner(System.in);


System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();


System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need: ");
numCups = scnr.nextFloat();

if (numCups > 1 && numCups <= MAX_CUPS){
System.out.println(numCups + " is a valid number of cups");
} else{
System.out.println(numCups + " is not a valid number of cups!");
System.out.println("Please enter a number of cups between 1 and 100:");
numCups = scnr.nextInt();
if (numCups >= 1 && numCups <= MAX_CUPS){
System.out.println(numCups + " is a valid number of cups!");
} else if(numCups <1){
System.out.println(numCups + " is less than 1. Sorry you are out of tries.");
} else if (numCups > 100) {
System.out.println(numCups + " is larger than 100. Sorry you are out of tries.");
}
}
}else{

System.out.println("Error: That is not a number.");

}

System.out.println("Please enter the number of calories per cup: ");
numCaloriesPerCup = scnr.nextInt();


totalCalories = (numCaloriesPerCup * numCups);
  
System.out.println("The total number of calories is " + totalCalories);

}
  

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the corrected code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: This could be much better if you are allowed to use a loop for validation, in that way, you could get rid of repeating statements to shorten the nested if else block. Let me know if you need. Also, the case of non numeric entry won’t be executed as there is no exception handler setup.

// IngedientClass.java

package ingeredientclass;

import java.util.Scanner;

public class IngedientClass {

              public static void main(String[] args) {

                           String nameOfIngredient = "";

                           double numCups = 0;

                           int numCaloriesPerCup = 0;

                           double totalCalories = 0.0;

                           final int MAX_CUPS = 100;

                           Scanner scnr = new Scanner(System.in);

                           System.out.println("Please enter the name of the ingredient: ");

                           nameOfIngredient = scnr.next();

                           System.out.println("Please enter the number of cups of "

                                                       + nameOfIngredient + " we'll need: ");

                           // getting initial value for number of cups

                           numCups = scnr.nextFloat();

                           // validation

                           if (numCups > 1 && numCups <= MAX_CUPS) {

                                         // valid

                                         System.out.println(numCups + " is a valid number of cups");

                           } else {

                                         // invalid, asking for one more time

                                         System.out.println(numCups + " is not a valid number of cups!");

                                         System.out

                                                                    .println("Please enter a number of cups between 1 and 100:");

                                         numCups = scnr.nextInt();

                                         // validating again

                                         if (numCups >= 1 && numCups <= MAX_CUPS) {

                                                       // valid

                                                       System.out.println(numCups + " is a valid number of cups!");

                                         } else if (numCups < 1) {

                                                       // invalid, displaying error message and quitting

                                                       System.out.println(numCups

                                                                                  + " is less than 1. Sorry you are out of tries.");

                                                       System.exit(0); // end of program

                                         } else if (numCups > 100) {

                                                       System.out.println(numCups

                                                                                  + " is larger than 100. Sorry you are out of tries.");

                                                       System.exit(0);// end of program

                                         }

                           }

                           // if the program reached here, the number of cups is valid, so asking

                           // for number of calories per cup

                           System.out.println("Please enter the number of calories per cup: ");

                           numCaloriesPerCup = scnr.nextInt();

                           // not validating number of calories per cup since not mentioned.

                           totalCalories = (numCaloriesPerCup * numCups);

                           System.out.println("The total number of calories is " + totalCalories);

              }

}

/*OUTPUT*/

Please enter the name of the ingredient:

mocha

Please enter the number of cups of mocha we'll need:

2400

2400.0 is not a valid number of cups!

Please enter a number of cups between 1 and 100:

99

99.0 is a valid number of cups!

Please enter the number of calories per cup:

3

The total number of calories is 297.0

Add a comment
Know the answer?
Add Answer to:
Java Branches code not working please HELP!! I am trying to build this class that will...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • How to build Java test class? I am supposed to create both a recipe class, and...

    How to build Java test class? I am supposed to create both a recipe class, and then a class tester to test the recipe class. Below is what I have for the recipe class, but I have no idea what/or how I am supposed to go about creating the test class. Am I supposed to somehow call the recipe class within the test class? if so, how? Thanks in advance! This is my recipe class: package steppingstone5_recipe; /** * *...

  • I would like someone to check my code and help with my for loop to print...

    I would like someone to check my code and help with my for loop to print the recipe. It is incorrect. package SteppingStones; import java.util.Scanner; //Scanner class// import java.util.ArrayList; //ArrayList// import ingredients.Ingredient; /**Gets from package ingredients and class Ingredient * * @author kimbe */ public class SteppingStone5_Recipe {    //Instance Variables// private ArrayList recipeIngredients; private String recipeName; private int servings; private double totalRecipeCalories;                   //Setter and Getters//    public ArrayList getrecipeIngredients() { return recipeIngredients; }...

  • Can someone help me with my code.. I cant get an output. It says I do...

    Can someone help me with my code.. I cant get an output. It says I do not have a main method. HELP PLEASE. The instruction are in bold on the bottom of the code. package SteppingStones; //Denisse.Carbo import java.util.Scanner; import java.util.ArrayList; import java.util.List; public class SteppingStone5_Recipe { private String recipeName; private int servings; private List<String> recipeIngredients; private double totalRecipeCalories; public String getRecipeName() { return recipeName; } public void setRecipeName (string recipeName){ this.recipeName = recipeName; } public int getServings() { return...

  • Prompt: In this stepping stone lab assignment, you will build a Recipe class, getting user input...

    Prompt: In this stepping stone lab assignment, you will build a Recipe class, getting user input to collect the recipe name and serving size, using the ingredient entry code from Stepping Stone Lab Four to add ingredients to the recipe, and calculating the calories per serving. Additionally, you will build your first custom method to print the recipe to the screen. Specifically, you will need to create the following:  The instance variables for the class (recipeName, serving size, and...

  • I am currently doing homework for my java class and i am getting an error in...

    I am currently doing homework for my java class and i am getting an error in my code. import java.util.Scanner; import java.util.Random; public class contact {       public static void main(String[] args) {        Random Rand = new Random();        Scanner sc = new Scanner(System.in);        System.out.println("welcome to the contact application");        System.out.println();               int die1;        int die2;        int Total;               String choice = "y";...

  • I need help on creating a while loop for my Java assignment. I am tasked to...

    I need help on creating a while loop for my Java assignment. I am tasked to create a guessing game with numbers 1-10. I am stuck on creating a code where in I have to ask the user if they want to play again. This is the code I have: package journal3c; import java.util.Scanner; import java.util.Random; public class Journal3C { public static void main(String[] args) { Scanner in = new Scanner(System.in); Random rnd = new Random(); System.out.println("Guess a number between...

  • I am working on this switch statement code and I am getting errors. Please help. import...

    I am working on this switch statement code and I am getting errors. Please help. import java.util.Scanner; public class Switchstatement { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } class Convertor { public static void main(String[] args) {    int choice;    Double Yen, UsDollars, Kilometer, Miles, Kilograms, Pounds, Inches; Double Centimeters, result;       Scanner scanner = new Scanner(System.in);    System.out.print("Enter 1\t UsDollars to Yen:...

  • I need help with the code below. I am getting an error message I am not...

    I need help with the code below. I am getting an error message I am not sure how to fix import java.util.Scanner; public class DriveTestExams { public static vice main (String[] args);{ Scanner KB = new Scanner (System.in); int IncorrectAns; String[]CA = {"A", "D", "B", "B", "C", "B","A", "B","C", "D","A", "C","D", "B","D", "C","C", "A","D", "A"}; String[]SA = new String [20]; Boolean RightChoice = true; int IncorrectAns = 0; for(int i=o; i <=20; i++){ while (rightchoices); System.out.prinlin ("please enter answer for...

  • JAVA: Rewrite the following code to where the inputs are from a file. The file name...

    JAVA: Rewrite the following code to where the inputs are from a file. The file name will be from the input from the user scanner. CODE: import java.util.*; public class Q1 { public static int sumOD (int k) { int sumOD = 0; int in = k; while (in != 0) { int digitON = in % 10; sumOD += digitON; in /= 10; } return sumOD; }    public static void main(String[] args) { int n, i, k; System.out.println("Enter...

  • Java Programming Question. I am writing a code to calculate the roots of the quadratic equation...

    Java Programming Question. I am writing a code to calculate the roots of the quadratic equation based on the values of the coefficients A, B, and C. I am supposed to enter 5 values for each coefficient, and the output should be five different answers (see example) using a for loop and if else statements. However, when I run my code, I am only able to enter one value for each coefficient and the output is one answer repeated five...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT