Merged with Java do while look proper coding return value?.
I am trying to return data from a freaky do while or the if statement loop and it will not return the items I set why?
// yesno to n for first loop through.
do {
System.out.println("Welcome Sales ID: " + salesID + " please enter the samsung TV sold: \n");
samsungProduct = scanValue.next();
System.out.println("Please enter your total TV sales amounts individually for today \n");
singleSale = scanValue.nextDouble();
totalSales = totalSales + singleSale;
totalItems = totalItems++;
System.out.println("Do you want to enter another sales total(Y/N): \n ");
yesNo = scanValue.next();
} while (!yesNo.equalsIgnoreCase("N"));
// get the items set inside of the do while loop.
// The system print out values are empty.
System.out.printf(salesID + " you entered a total of: " + totalItems + "With a total sales of $%15.2f" + totalSales);
Related
I am very new to java and am trying to learn how to program it while working remotely which is very difficult for me. The assignment is to create an "ingredient" class that will ask for ingredients, validate the input, and then at the end print a list of ingredients. I have written and re-written this code about a dozen times and it never prints out correctly. It takes one too many loops through to get a correct output, and when the values stored in the variables during the execution print out incorrectly. This group is my last ditch effort as I am struggling so hard even though I'm putting in the work! Thanks again and take care.
package Stepping_Stones_Lab_2;
import java.util.Scanner;
import java.util.ArrayList;
public class MilestoneOne {
/**
*
*/
public static void main(String[] args) {
ArrayList<String> ingredientList = new ArrayList();
ArrayList<String> recipeList = new ArrayList();
//variable declaration
double ingredientAmount = 0.0;
double totalCalories = 0.0;
int numberCaloriesPerUnit = 0;
String recipeName;
String nameOfIngredient;
String unitMeasurement;
Scanner scnr = new Scanner(System.in);
boolean addMoreIngredients = true;
//recipie creation
System.out.print("Please enter your new recipe name: ");
recipeName = scnr.nextLine();
recipeList.add(recipeName);
//This do-while loop is requesting ingredients until such time the user terminates the requests by typing n. If neither y or n is
//used the program will return an Invalid value error
do {
System.out.print("Would you like to enter an ingredient: (y or n): ");
String reply = scnr.next().toLowerCase();
scnr.nextLine();
//the notes says use a switch but I have not been able to get a switch to work successfully despite many tries.
if(reply.equals("y")) {
System.out.print("Enter ingredient name: ");
nameOfIngredient = scnr.nextLine();
while (!nameOfIngredient.matches("[a-zA-Z_]+")){ //Validates input and loops until there is acceptable input for name
System.out.print("Error: Please enter valid name of ingredient: ");
nameOfIngredient = scnr.next();
}
ingredientList.add(nameOfIngredient);
System.out.println("Good job! The ingredient you entered is " + nameOfIngredient);
//Unit of measurement input and data validation
System.out.print("Please enter the unit of measurement (cups, ounces, etc.): ");
unitMeasurement = scnr.next();
while (!unitMeasurement.matches("[a-zA-Z_]+")){ //Validates input and loops until there is acceptable input for unit measurement
System.out.print("Error: Please enter valid unit of measurement: ");
unitMeasurement = scnr.next();
}
System.out.println("Good job! The unit of measurement for " + nameOfIngredient + " is " + unitMeasurement);
//Amount of ingredient input and data validation
System.out.print("Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we'll need: ");
while (!scnr.hasNextDouble()){//Validates input and loops until there is acceptable input for amount
System.out.print("Error: Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we'll need using numbers only: ");
scnr.next();
}
ingredientAmount = scnr.nextDouble();
System.out.println("Good job! The number of " + unitMeasurement + " of " + nameOfIngredient + " needs is " + ingredientAmount);
//Number of calories per cup of ingredient input and data validation
System.out.print("Please enter the number of calories per " + unitMeasurement + " of " + nameOfIngredient + ": ");
while (!scnr.hasNextInt()){
System.out.print("Please enter the number of calories per " + unitMeasurement + " of " + nameOfIngredient + " using numbers only: ");
scnr.next();
}
numberCaloriesPerUnit = scnr.nextInt();
System.out.println("Good job! The number of calories per " + unitMeasurement + " of " + nameOfIngredient + " is " + numberCaloriesPerUnit);
totalCalories = ingredientAmount * numberCaloriesPerUnit;
System.out.println(recipeName + " uses " + ingredientAmount + " " + unitMeasurement + " and has " + totalCalories + " calories.");
}
else if(reply.equals("n")){
addMoreIngredients = false;
System.out.println("Your ingredients for " + recipeName + " are as follows: ");
}
else {
System.out.println("Invalid value!!");
}
}
while (addMoreIngredients);
for (int i = 0; i < ingredientList.size(); i++) {
String ingredient = ingredientList.get(i);
System.out.println(ingredient);
}
}
}
It works for me. Look at the following transcript.
Please enter your new recipe name: recipe name
Would you like to enter an ingredient: (y or n): y
Enter ingredient name: a
Good job! The ingredient you entered is a
Please enter the unit of measurement (cups, ounces, etc.): b
Good job! The unit of measurement for a is b
Please enter the number of b of a we'll need: 2
Good job! The number of b of a needs is 2.0
Please enter the number of calories per b of a: 3
Good job! The number of calories per b of a is 3
recipe name uses 2.0 b and has 6.0 calories.
Would you like to enter an ingredient: (y or n): y
Enter ingredient name: a2
Error: Please enter valid name of ingredient: aa
Good job! The ingredient you entered is aa
Please enter the unit of measurement (cups, ounces, etc.): bb
Good job! The unit of measurement for aa is bb
Please enter the number of bb of aa we'll need: 4
Good job! The number of bb of aa needs is 4.0
Please enter the number of calories per bb of aa: 8
Good job! The number of calories per bb of aa is 8
recipe name uses 4.0 bb and has 32.0 calories.
Would you like to enter an ingredient: (y or n): n
Your ingredients for recipe name are as follows:
a
aa
I have the following simple sales program and am having trouble creating a restart loop around the program. My primary issue is converting the boolean from a string to a boolean type, I am getting an error in Eclipse that says, "The method parseBoolean(String) is undefined for the type Boolean".
However, I have defined a boolean variable at the top, boolean tryAgain = false;
and for some reason I cannot set the user input scanner to take the True or False value without an error. The error is occurring with the last line when I try to cast the nextLine from the user to boolean.
import java.util.Scanner;
public class Sales {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user input
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
while (tryAgain) {
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (True or False)");
tryAgain = Boolean.parseBoolean(userInput.nextLine());
}
}
}
The reason it gives you trouble is that when the user enters a double then hits enter, two things have just been entered - the double and a "newline" which is \n.
The method you are calling, "nextDouble()", only reads in the double, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you have to call nextLine() before your code would work.
Add this line before last line .
userInput.nextLine();
Well, I couldn't get it to work with a boolean for some reason, so I changed to a do while loop. Here is the final code. Also I did use the tip for clearing out the nextLine().
import java.util.Scanner;
public class Sales2 {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user inputjea
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
String answer; //Define var type of String for do while loop to restart program
do { //Do this loop while string == (last line of code while loop)
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (yes or no)"); //Prompt user for restart
userInput.nextLine(); //Clear scanner
answer = userInput.nextLine();
}
while (answer.equalsIgnoreCase("Yes")); //Connected to do while loop
//
}
}
Scanner supports nextBoolean(). Just use it:
tryAgain = userInput.nextBoolean()
I apologize if my question is confusing, I'll try to explain it better here.
I'm creating a Property Calculator where the user is required to enter the Rooms of the residence, the area of each room, and then the price. Which ultimately gets calculated (total area from each room * price).
I'm not too familiar with Java so I'm not sure why I'm unable to use the variable declared in the class, outside.
Here is the code, followed by the issue that is happening:
EDIT
package realestatepropvalue;
import java.util.Scanner;
public class RealEstateProbValueA3
{
public static void main(String[] args)
{
Scanner sc = new Scanner ( System.in );
System.out.println ( "Hello friend, you will enter a series "
+ "of fields that'll calculate your Real Estate Property Value.");
System.out.print ("Please enter a Street Number ");
String streetnum = sc.next();
sc.nextLine();
System.out.println ("You entered the Street Number, " +streetnum );
System.out.print ( "Please enter a Street Name ");
String streetnam = sc.nextLine();
System.out.println ("You entered the Street Name, " + streetnam + " " );
END EDIT
System.out.print ("Please enter the number of rooms! (Up to 5!) ");
int roomcount = sc.nextInt();
String[] places = new String[roomcount];
for(int i = 0; i < places.length; i++) {
places[i] = "Place Number: " + i;
}
sc.nextLine();
System.out.println("You said that there were " + roomcount + " rooms!");
System.out.print ("Please enter the types of rooms (up to " +roomcount+ ") that fill up the " + roomcount + " rooms!\n"
+ "(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!) \n ") ;
int squareCounter = 0;
String[] types = new String[roomcount];
for(int i = 1; i < types.length; i++) {
System.out.print ("Please enter the types of room " + places[i] + ": ");
String roomName = sc.nextLine();
types[i] = roomName;
System.out.print ("Please enter the square feet of " + roomName + ": ");
int squareFeet = sc.nextInt();
squareCounter = squareFeet + squareCounter;
System.out.println("Room name: " + roomName + " is: " + squareFeet + "square feet.");
System.out.println("The counter total: " + squareCounter );
System.out.println("What is the price per sq. feet?");
int pricePer = sc.nextInt();
int finalCalc = pricePer * squareCounter;
System.out.println( "Estimated Property value: $____" + finalCalc);
}
Here is the log:
LOG EDIT
run:
Hello friend, you will enter a series of fields that'll calculate your Real
Estate Property Value.
Please enter a Street Number 7
You entered the Street Number, 7
Please enter a Street Name Washington Street
You entered the Street Name, Washington Street
END EDIT
Please enter the number of rooms! (Up to 5!) 3
You said that there were 3 rooms!
Please enter the types of rooms (up to 3) that fill up the 3 rooms!
(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!)
Please enter the types of room Place Number: 1: Kitchen
Please enter the square feet of Kitchen: 50
Room name: Kitchen is: 50square feet.
The counter total: 50
What is the price per sq. feet?
50
Estimated Property value: $____2500
Please enter the types of room Place Number: 2: Please enter the square feet of :
The last line immediately skips the type of room, and asks the square feet. Why does this happen?
Thank you for any help!
So for my computer science class we have to make a gpa calculator and include an applet in the same program to display the full name of the student and their GPA. I have the program working
import java.util.*;
import java.text.DecimalFormat;
import javax.swing.JApplet;
import java.awt.*;
public class Project1_Michael_Micool extends JApplet
{
public static void main(String[]args)
{
String first_name, last_name, course1, course2, course3, course4;
//Sets all the needed variables to string values for first, last and course names
int cred_course1, cred_course2, cred_course3, cred_course4, total_credits;
//Sets all the course credits as int values
float grade_course1, grade_course2, grade_course3, grade_course4, grade_point1, grade_point2, grade_point3, grade_point4, total_grades_added, gpa;
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("0.##");
System.out.println("Welcome to the UNG GPA calculator.");
System.out.println();
System.out.println("Please enter your first name");
first_name = scan.next(); //Assigns the entered name as first_name
System.out.println("Please enter your last name");
last_name = scan.next(); //Assigns the entered name as last_name
System.out.println();
System.out.println("A: 4.0 A-:3.67 ");
System.out.println("B+:3.33 B:3.00 B-:2.67");
System.out.println("C+: 2.33 C:2.00 C-:1.67");
System.out.println("D+: 1.33 D:1.00 F:0.00");
System.out.println();
System.out.println("Please enter your first course name and number. EX: PSYC1101");
course1 = scan.next();
System.out.println("Please enter the number of credits for course 1.");
cred_course1 = scan.nextInt();
System.out.println("Please enter your grade for course 1 using the chart. EX: B+= 3.33");
grade_course1 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your second course name and number. EX: PSYC1101");
course2 = scan.next();
System.out.println("Please enter the number of credits for course 2.");
cred_course2 = scan.nextInt();
System.out.println("Please enter your grade for course 2 using the chart. EX: B+= 3.33");
grade_course2 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your third course name and number. EX: PSYC1101");
course3 = scan.next();
System.out.println("Please enter the number of credits for course 3.");
cred_course3 = scan.nextInt();
System.out.println("Please enter your grade for course 3 using the chart. EX: B+= 3.33");
grade_course3 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your fourth course name and number. EX: PSYC1101");
course4 = scan.next();
System.out.println("Please enter the number of credits for course 4.");
cred_course4 = scan.nextInt();
System.out.println("Please enter your grade for course 4 using the chart. EX: B+= 3.33");
grade_course4 = scan.nextFloat();
total_credits = cred_course1 + cred_course2 + cred_course3 + cred_course4;
grade_point1 = grade_course1 * cred_course1;
grade_point2 = grade_course2 * cred_course2;
grade_point3 = grade_course3 * cred_course3;
grade_point4 = grade_course4 * cred_course4;
total_grades_added = grade_point1 + grade_point2 + grade_point3 + grade_point4;
gpa = total_grades_added / total_credits;
gpa = Math.abs(gpa);
course1 = course1.toUpperCase();
course2 = course2.toUpperCase();
course3 = course3.toUpperCase();
course4 = course4.toUpperCase();
System.out.println("Your name is " + first_name + " " + last_name);
System.out.println("You are taking " + course1 + " which is worth " + cred_course1 + " credit hours");
System.out.println("You are taking " + course2 + " which is worth " + cred_course2 + " credit hours");
System.out.println("You are taking " + course3 + " which is worth " + cred_course3 + " credit hours");
System.out.println("You are taking " + course4 + " which is worth " + cred_course4 + " credit hours");
System.out.println("Your total credit hours is " + total_credits);
System.out.println("Your GPA is " + fmt.format(gpa));
}
}
Here is the applet that I think should work.
public void paint(Graphics page)
{
page.drawString(first_name + " " + last_name, 110, 70);
page.drawString(gmt.format(gpa), 130, 100);
}
So my question is, how to you incorporate the applet into the program?
What you posted is not an "Applet"; it's just the paint method of something that might be an AWT widget (e.g. an applet). Just use that method in a widget that you integrate into your UI.
An Applet (or JApplet) would not typically have a main(String[]) unless it is an hybrid application/applet (where the application is based around a Frame or JFrame), but that main method is focused on the command line.
There is no practical way to use the command line code in either an applet or an application. It needs to be rewritten to use a GUI.
..for my computer science class..
Please refer the instructor to Why CS teachers should stop teaching Java applets.
I've written this program but am running into a logical error upon compilation.
My input would be 1, 2, 6, 10 for the selection of products and the coinciding output should be
Total items ordered: 3
Price of items ordered: $747.00
Sales Tax: $48.55
Total amount due: $795.55
Strangely enough it is giving me
Total items ordered: 3
Price of items ordered: $6611.00
Sales Tax: $429.715
Total amount due: $7040.715
Is there an error within my for loop conditions or calculations, or my array that is leading to this hyper-inflated output?
import java.util.Scanner;
public class GrapefruitOrderingArray {
//Declare Constants
public static final int SIZE = 100;
public static final int[] itemPrices = {49,299,329,399,199,1299,1199,999,599};
public static void main(String[] args) {
// Declare Variables
Scanner input = new Scanner (System.in);
String CustomerName;
int[] naNumber = new int [SIZE];
int nProducts = 0;
double nTotal = 0;
double dFinalPrice = 0.0;
int nCount = 0;
//Declare Constants
final int SENTINEL = 10;
final double SALES_TAX = 0.065;
//Prompt user to enter name
System.out.println("Please enter your name: ");
//Enter user name
CustomerName = input.nextLine();
System.out.println("");
//Begin Product Listing Declarations with respect to array above
System.out.println("GRAPEFRUIT PRODUCT:");
System.out.println("1. gPod shuffle $" + itemPrices[0]);
System.out.println("2. gPod Touch $" + itemPrices[1]);
System.out.println("3. gPad Mini $" + itemPrices[2]);
System.out.println("4. gPad 2 $" + itemPrices[3]);
System.out.println("5. gPhone $" + itemPrices[4]);
System.out.println("6. gMac $" + itemPrices[5]);
System.out.println("7. MacNovel Pro $" + itemPrices[6]);
System.out.println("8. MacNovel Air $" + itemPrices[7]);
System.out.println("9. MiniMac $" + itemPrices[8]);
System.out.println("10. Complete my order");
//Keep reading until the input is terminated by sentinel
System.out.println("\nPlease select an item from the menu above: ");
//Read number entered by the user
naNumber[nCount] = input.nextInt();
//Begin while-loop statement
while (naNumber[nCount] != SENTINEL) {
System.out.println("\nPlease select another item from the menu above: ");
nCount++;
//Read number entered by the user
naNumber[nCount] = input.nextInt();
}
System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName);
//Call final price calculation
dFinalPrice = calculateTotalPrice(naNumber,itemPrices,nTotal);
//Print blank line to screen
System.out.println("");
//Total amount of product ordered
System.out.println("Total items ordered: " + nCount );
//Total price of items ordered
System.out.println("Price of items ordered: $" + dFinalPrice );
//Sales tax associated with the purchase
System.out.println("Sales tax: $" + SALES_TAX * dFinalPrice );
//Total amount due by the customer to Grapefruit Co.
System.out.println("Total amount due: $" + (SALES_TAX * dFinalPrice + dFinalPrice ));
} //End main method
private static double calculateTotalPrice(int[] naNumber, int[] itemPrices) {
double total = 0;
//Calculate entered items
for(int i = 0; i < naNumber.length; i++){
if(naNumber[i] != 0) {
total += itemPrices[naNumber[i] - 1];
}
}
return total;
}
} //end class calculateTotalPriceOfItemsOrdered
You naNumber will contain numbers from 1 to 9. This means that you'll be multiplying the item prices by some large numbers at some points, hence why you're getting large totals.
What I think you want to do is
double itemTotal = itemPrices[naNumber[i] - 1];
nTotal += itemTotal;
Without multiplying itemPrices[i] by naNumber[i]
Also you don't really need to pass nTotal to the method and initialise a double with every loop. You can just declare a field outside the loop:
double total = 0;
Use it inside the loop like this:
total += itemPrices[naNumber[i] - 1];
And return it at the end of the method.
So your method would look something like that:
private static double calculateTotalPrice(int[] naNumber, int[] itemPrices) {
double total = 0;
//Calculate entered items
for(int i = 0; i < naNumber.length; i++){
if(naNumber[i] != 0) {
total += itemPrices[naNumber[i] - 1];
}
}
return total;
}
There are three problems here.
You put the sentinel value, 10, into the array of items the user has chosen.
You use the loop index rather than the number the user chose when calculating price.
You multiply the price of each item by its number. So the user buys 6 of item 6.
In your main method, you need to read the user's input into another variable, and only insert it into the array if it is not the sentinel value.
In your calculateTotalPrice method, you should calculate the price of an individual line item like this:
double itemTotal = itemPrices[naNumber[i] - 1];