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; /** * *...

  • 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...

  • 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...

  • Hi. Could you help me with the code below? I need to validate the code below, using expressions that can carry out the actions or that make appropriate changes to the program’s state, using conditiona...

    Hi. Could you help me with the code below? I need to validate the code below, using expressions that can carry out the actions or that make appropriate changes to the program’s state, using conditional and iterative control structures that repeat actions as needed. The unit measurement is missing from the final output and I need it to offer options to lbs, oz, grams, tbsp, tsp, qt, pt, and gal. & fl. oz. Can this be added? The final output...

  • Provide comments for this code explaining what each line of code does import java.util.*; public class...

    Provide comments for this code explaining what each line of code does import java.util.*; public class Chpt8_Project {    public static void main(String[] args)       {        Scanner sc=new Scanner(System.in);        int [][]courses=new int [10][2];        for(int i=0;i<10;i++)        {            while(true)            {                System.out.print("Enter classes and graduation year for student "+(i+1)+":");                courses[i][0]=sc.nextInt();                courses[i][1]=sc.nextInt();                if(courses[i][0]>=1...

  • Hi so I am currently working on a project for a java class and I am...

    Hi so I am currently working on a project for a java class and I am having trouble with a unit testing portion of the lab. This portion wants us to add three additional tests for three valid arguments and one test for an invalid argument. I tried coding it by myself but I am not well versed in unit testing so I am not sure if it is correct or if the invalid unit test will provide the desired...

  • Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args)...

    Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn);    else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...

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
ADVERTISEMENT