I was wondering if someone could tell me
1. why, when i input weightNumber with a decimal place, weightConverted doesn't convert it to the whole number, even though I create variable for it?
2. how could i improve this "program" in any way, THANK YOU !!
here is the problem:
code:
import java.util.Scanner;
public class cofee {
public static void main (String []args){
double weightNumber = 0;
String packageType = "";
String serviceType ="";
double totalFee = 0;
double weightConverted = Math.round(weightNumber); // <- this is the problem, should i put it somewhere else?
final double LETTERCOSTP = 12.00;
final double LETTERCOSTS = 10.50;
final double BOXCOSTP = 15.75;
final double BOXCOSTS = 13.75;
final double BOXWEIGHTP = 1.25;
final double BOXWEIGHTS = 1.00;
// input
Scanner input = new Scanner(System.in);
System.out.print("Enter package type (letter/box): ");
packageType = input.nextLine().toLowerCase();
System.out.print("Enter type of service (standard/priority): ");
serviceType = input.nextLine().toLowerCase();
switch(packageType)
{
case "letter":
System.out.print("Enter the weight in ounces: ");
weightNumber = input.nextDouble();
break;
case "box":
System.out.print("Enter the weight in pounds: ");
weightNumber = input.nextDouble();
break;
default:
System.out.print("WRONG PACKAGE TYPE !!!");
}
// letter
if (packageType.equals("letter") && serviceType.equals("priority"))
{
totalFee = LETTERCOSTP;
}
if (packageType.equals("letter") && serviceType.equals("standard"))
{
totalFee = LETTERCOSTS;
}
// box
if (packageType.equals("box") && serviceType.equals("priority"))
{
totalFee = BOXCOSTP + ((weightConverted - 1.0) * BOXWEIGHTP);
}
if (packageType.equals("box") && serviceType.equals("standard"))
{
totalFee = BOXCOSTS + ((weightConverted - 1.0) * BOXWEIGHTS);
}
// display
System.out.println("The fee is € "+ totalFee + " for a package with");
System.out.println("\tType: "+packageType);
System.out.println("\tService: "+serviceType);
System.out.println("\tOunces: "+weightConverted);
}
}
The line double weightConverted = Math.round(weightNumber); will call round() with the value of weightNumber, which is 0, so it rounds 0 to... well... 0, and assigns it to weightConverted.
Related
I'm here doing an assignment and I'm getting a problem
A red mark is coming up next to "TotalCharge = ptr.calculateCharge(NightsStay, perNight);" and the error is double cannot be converted to Integer.
I tried researching to solve the problem but nothing is working.
Thank you very much.
HiibiscusHotelSpa9674 ptr = new HiibiscusHotelSpa9674();
Scanner keyboard = new Scanner(System.in);
Integer compare = 0;
String response = null;
String number = null;
Double Price = 0.00;
Integer TotalCharge = 0;
Integer ItemNo = 0;
String surName;
Integer perNight = 0;
Integer roomNumber = 0;
Double amountPaid = 0.0;
String temp = null;
String Name = null;
Double cashPaid = 0.0;
Double Change = 0.0;
Integer NightsStay = 0;
temp = JOptionPane.showInputDialog("Enter The amount of Items :");
int Size = Integer.parseInt(temp);
String[] ItemName = new String[Size];
Integer[] ItemId = new Integer[Size];
double[] ItemPrice = new double[Size];
Integer index = 0;
while (index < Size) {
ItemName[index] = JOptionPane.showInputDialog("Enter The Item Name:");
temp = JOptionPane.showInputDialog("Enter Item ID for " + ItemName[index] + " :");
ItemId[index] = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Enter The Price for " + ItemName[index] + " :");
ItemPrice[index] = Double.parseDouble(temp);
index++;
ptr.displayMenu(ItemName, ItemId, ItemPrice);
Name = ptr.getDataSetA();
cashPaid = ptr.getDataSetB(ItemId);
Change = ptr.performCalc(cashPaid, ItemPrice);
ptr.displayResults(Change, cashPaid);
response = JOptionPane.showInputDialog("Sale Complete? Enter Y or N: ");
switch (response) {
case "N":
perNight = ptr.GetGuestInfo();
NightsStay = ptr.GetDate();
TotalCharge = ptr.calculateCharge(NightsStay, perNight);
ptr.displayGuestBill(NightsStay, TotalCharge);
break;
case "n":
perNight = ptr.GetGuestInfo();
NightsStay = ptr.GetDate();
TotalCharge = ptr.calculateCharge(NightsStay, perNight);
ptr.displayGuestBill(NightsStay, TotalCharge);
break;
default:
JOptionPane.showMessageDialog(null, "Thank you very much and haave a wonderful day!");
}
public void displayMenu(String Name[], Integer ItemId[], double Price[]) {
System.out.printf("Item Name Item ID ItemPrice\n");
for (int i = 0; i < Name.length; i++) {
System.out.printf("%s\t %d\t %.2f\t\n", Name[i], ItemId[i], Price[i]);
}
}
public String getDataSetA() {
Scanner keyboard = new Scanner(System.in);
String[] personalInformation = new String[2];
String NameRoomNumber = null;
System.out.printf("Please Enter Room Number\n");
personalInformation[1] = keyboard.next();
System.out.printf("Enter your Surname\n");
personalInformation[0] = keyboard.next();
String NameNumber = Arrays.toString(personalInformation);
return NameRoomNumber;
}
private Double getDataSetB(Integer[] ItemId) {
Scanner keyboard = new Scanner(System.in);
String temp = null;
for (int i = 0; i < ItemId.length; i++) {
double cashPaid = 0.0;
Integer[] Items = new Integer[ItemId.length];
System.out.println("Please Enter the Item ID for the item");
ItemId[i] = keyboard.nextInt();
}
System.out.printf("Please Enter Cash Paid\n");
double cashPaid = keyboard.nextDouble();
return cashPaid;
}
private double performCalc(double cashPaid, double[] Price) {
Scanner keyboard = new Scanner(System.in);
double Cost = 0.0;
double change = 0.0;
double moneyOwe = 0.0;
for (int i = 0; i < Price.length; i++) {
Cost = Cost + Price[i];
}
if (cashPaid < Cost) {
moneyOwe = Cost - cashPaid;
JOptionPane.showMessageDialog(null, "You are $" + moneyOwe + " short");
} else {
change = cashPaid - Cost;
}
return change;
}
private void displayResults(Double Change, Double cashPaid) {
JOptionPane.showMessageDialog(null, "Cash Paid:$ " + cashPaid + "Change:$ " + Change + ".");
}
private Integer GetGuestInfo() {
String temp = null;
String Guestname = null;
Integer FloorNum = 0;
Integer NoofPer = 0;
Guestname = JOptionPane.showInputDialog("Please Enter Guest Name");
temp = JOptionPane.showInputDialog("Enter Floor Required");
FloorNum = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please Enter The Number of Persons Staying with you");
NoofPer = Integer.parseInt(temp);
return NoofPer;
}
private Integer GetDate() {
String temp = null;
Integer day = 0;
Integer month = 0;
Integer year = 0;
Integer Nights = 0;
temp = JOptionPane.showInputDialog("Please enter the Day: ");
day = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the Month: ");
month = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the Year: ");
year = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the number of Nights staying:");
Nights = Integer.parseInt(temp);
return Nights;
}
private Double calculateCharge(Integer amtofNights, Integer perNight) {
Integer floor = 0;
double totalCharge = 0.0;
if (floor > 4) {
// int perNight = 0;
int Numofnights = 0;
totalCharge = 150 * perNight * amtofNights;
} else {
totalCharge = 100 * perNight * amtofNights;
}
return totalCharge;
}
private void displayGuestBill(Integer NightsStayed, Integer totalCharge) {
System.out.printf("The total number of nights:%d\n", NightsStayed);
System.out.printf("The total Charge:%d", totalCharge);
}
}
Double is a wrapper class on top of the primitive double. It can be cast to double, but it cannot be cast to int directly.
If you use double instead of Double, it will compile:
double d = 10.9;
int i = (int)(d);
You can not convert a double to an integer implictely, because you are loosing precision. Imagine converting 3.7 to an integer, you would get 3 but a significant amount of information got lost.
If you are fine with this, you can do an explicit cast with (int)some_double for example.
Your code example does not contain any types, which makes it hard to say at which place your conversion happens.
Edit: Since your code example now contains types, it looks likely that your calculateCharge returns a double, but you are storing it into an integer.
You should force the explicit cast by doing
TotalCharge = (int)ptr.calculateCharge(NightsStay, perNight);
I have received four error messages in my code. It states that in modes 2 and 4, dArea cannot be resolved to a variable. Later in the code, the same variable is said to be duplicated even though it has only been assigned value, used, and returned. How can I fix these issues?
import javax.swing.JOptionPane;
public class Lab7
{
public static void main(String args [])
{
// Created by Makayla Scull, period 4B
String sMode;
int iMode = 0;
sMode = JOptionPane.showInputDialog("Menu: \n [Square: Press 1] \n [Rectangle: Press 2] \n [Circle: Press 3] \n [Triangle: Press 4] \n [Trapezoid: Press 5] \n [To Exit: Press 6]");
iMode = Integer.parseInt(sMode);
while(iMode == 0);
{
if (iMode == 1)
{
Geometry.methodSquare();
}
if (iMode == 2)
{
Geometry.methodRectangle(dArea);
}
if (iMode == 3)
{
Geometry.methodCircle();
}
if (iMode == 4)
{
Geometry.methodTriangle(dArea);
}
if (iMode == 5)
{
Geometry.methodTrapezoid();
}
if (iMode == 6)
{
break;
}
}
}
}
class Geometry
{
public static void methodSquare()
{
String sLength;
double dLength;
double dArea;
int exp = 2;
JOptionPane.showMessageDialog(null, "You chose the square.");
sLength = JOptionPane.showInputDialog("Enter the side length of the square.");
dLength = Double.parseDouble(sLength);
dArea = Math.pow(dLength, exp);
JOptionPane.showMessageDialog(null, "The area of the square is " + dArea);
}
public static double methodRectangle(double dArea)
{
String sLength;
String sWidth;
double dLength;
double dWidth;
JOptionPane.showMessageDialog(null, "You chose the rectangle.");
sLength = JOptionPane.showInputDialog("Enter the length of the rectangle.");
sWidth = JOptionPane.showInputDialog("Enter the width of the rectangle.");
dLength = Double.parseDouble(sLength);
dWidth = Double.parseDouble(sWidth);
double dArea = (dLength * dWidth);
JOptionPane.showMessageDialog(null, "The area of the rectangle is " + dArea);
return dArea;
}
public static double methodCircle()
{
String sRadius;
double dRadius;
int exp = 2;
JOptionPane.showMessageDialog(null, "You chose the circle.");
sRadius = JOptionPane.showInputDialog("Enter the radius of the circle.");
dRadius = Double.parseDouble(sRadius);
double dArea = Math.pow(dRadius, exp) * Math.PI;
JOptionPane.showMessageDialog(null, "The area of the circle is " + dArea);
return dArea;
}
public static double methodTriangle(double dArea)
{
String sBase;
String sHeight;
double dBase;
double dHeight;
JOptionPane.showMessageDialog(null, "You chose the triangle.");
sBase = JOptionPane.showInputDialog("Enter the base length of the triangle.");
dBase = Double.parseDouble(sBase);
sHeight = JOptionPane.showInputDialog("Enter the height of the triangle.");
dHeight = Double.parseDouble(sHeight);
double dArea = (dBase * dHeight) / 2;
JOptionPane.showMessageDialog(null, "The area of the triangle is " + dArea);
return dArea;
}
public static void methodTrapezoid()
{
String sHeight;
String sBase1;
String sBase2;
double dHeight;
double dBase1;
double dBase2;
JOptionPane.showMessageDialog(null, "You chose the trapezoid.");
sHeight = JOptionPane.showInputDialog("Enter the height of the trapezoid.");
dHeight = Double.parseDouble(sHeight);
sBase1 = JOptionPane.showInputDialog("Enter the length of the first base of the trapezoid.");
dBase1 = Double.parseDouble(sBase1);
sBase2 = JOptionPane.showInputDialog("Enter the length of the second base of the trapezoid.");
dBase2 = Double.parseDouble(sBase2);
double dArea = ((dBase1 + dBase2) * dHeight) / 2;
JOptionPane.showMessageDialog(null, "The area of the trapezoid is " + dArea);
}
}
in modes 2 and 4, dArea cannot be resolved to a variable
That's because you never defined that variable. You try to use it:
Geometry.methodRectangle(dArea);
But nowhere in that scope have you defined it. A value has to exist before it can be used.
the same variable is said to be duplicated
Your methods define a variable as a parameter to the method:
public static double methodRectangle(double dArea)
But then also try to declare it again within the method:
double dArea = (dLength * dWidth);
Just as the error is telling you, a variable can only be declared once in any given scope. If you try to have two variables by the same name in the same scope then the compiler would have no way of knowing which one you're referring to.
Need to set a maximum (100) and minimum (0), for this average test result program. I understand that i would need to use '<' and'>' somewhere within my work however i am not sure how/where
import java.util.Scanner;
public class ExamResults {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the 5 exam results");
double ExamResult1 = 0.0;
ExamResult1 = Double.parseDouble(keyboard.nextLine());
double ExamResult2 = 0.0;
ExamResult2 = Double.parseDouble(keyboard.nextLine());
double ExamResult3 = 0.0;
ExamResult3 = Double.parseDouble(keyboard.nextLine());
double ExamResult4 = 0.0;
ExamResult4 = Double.parseDouble(keyboard.nextLine());
double ExamResult5 = 0.0;
ExamResult5 = Double.parseDouble(keyboard.nextLine());
double averageScore;
averageScore = ((ExamResult1 + ExamResult2 + ExamResult3 + ExamResult4 + ExamResult5)/5);
System.out.println("The average Score is" + averageScore);
}
}
Try something like:
double min = Math.min(Math.min(ExamResult1, ExamResult2), ExamResult3);//similarly for others
double max = Math.max(Math.max(ExamResult1, ExamResult2), ExamResult3);//similarly for others
I would do this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the 5 exam results");
double[] examResults = new double[5];
double total = 0.0;
for (int i = 0; i < examResults.length; i++)
{
double value = Double.parseDouble(keyboard.nextLine());
while (value < 0 || value > 100)
{
System.out.println("Invalid score, try again");
value = Double.parseDouble(keyboard.nextLine());
}
examResults[i] = value;
total += value;
}
double averageScore;
averageScore = total / examResults.length;
System.out.println("The average Score is" + averageScore);
I cannot find out where my mathematical error is. I just cannot see why I continue to receive no values back for my determineCableSrvs method.
private static Scanner input = new Scanner(System.in); //STORES CUSTOMER NAME STRING VALUE
public static void main(String[] args)
{//BEGIN main()
//Variables
int subscription = 0; //STORES SUBSCRIPTION INTEGER VALUE
int moviesOnDemand = 0; //STORES MOVIES ON DEMAND INTEGER VALUE
double cableSrvs = 0; //STORES TOTAL CABLE SERVICE DECIMAL VALUE
double totalMovieCharges = 0; //STORES TOTAL MOVIE CHARGES DECIMAL VALUE
double total = 0; //STORES TOTAL DECIMAL VALUE
char confirm = 'Y'; //LOOP CONTROL VARIABLE SET TO Y
Calendar dateTime = Calendar.getInstance(); //STORES THE DATE VALUE
String customerName = "";
while(Character.toUpperCase(confirm) == 'Y') //START OF WHILE LOOP AUTOMATICALLY ENTERS
{
String customer = setCustNm(customerName);
double cable = setCablePkg(subscription);
double type = determineCableSrv(subscription, cableSrvs);
int movies = setMoviePurchase(moviesOnDemand);
totalMovieCharges = movies * 7; //CALCULATING THE TOTAL MOVIE ON DEMAND CHARGE
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
input.nextLine();
askNewSubscription(confirm);
printThankYou(confirm);
}
}
public static String setCustNm(String customerName)
{
// 1st prompt
System.out.printf("%n%n%nWELCOME TO SA CABLE %n");
System.out.printf("%nPlease enter your name: "); //PROMPTING USER TO ENTER NAME
customerName = input.nextLine(); //CAPTURES USERS NAME
return customerName;
}
public static int setCablePkg(int subscription)
{
do{
// 2nd Prompt DISPLAYING THE DIFFERENT PACKAGES AVAILABLE FOR SUBSCRIPTION
System.out.printf("%nSA CABLE - SUBSCRIPTION PACKAGES " +
"%n%n1. Basic: Local & major TV network channels %s" +
"%n2. Deluxe: Local, major TV, cable & 100 other channels %s" +
"%n3. Premium: Deluxe package plus HEB, on-demand & 300 other channels %s",
"$35.00", "75.00", "110.00") ;
System.out.printf("%n%nSelect your cable subscription package: ");
subscription = input.nextInt();//CAPTURING USER INPUT
}while (subscription < 1 || subscription > 3);
return subscription;
}
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
public static int setMoviePurchase(int moviesOnDemand)
{
System.out.printf("%nSA CABLE - MOVIES " +
"%n%nEnter the number of Movies-On-Demand-HD purchases: ");
moviesOnDemand = input.nextInt();
return moviesOnDemand;
}
public static char askNewSubscription(char confirm)
{
System.out.printf("\nEnter 'Y' to continue with a new subscription or 'N' to exit: ");
confirm = input.nextLine().charAt(0);
return confirm;
}
public static char printThankYou(char confirm)
{
if(Character.toUpperCase(confirm) == 'Y')
{
confirm = 'Y';
}
if (Character.toUpperCase(confirm) != 'Y')
{
confirm = 'N';
System.out.printf("Thank you for being a valued SA Cable customer!");
System.exit(0);
}
return confirm;
}
I'm having trouble with this part:
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
Here is how I'm calling the method:
double type = determineCableSrv(subscription, cableSrvs);
I cannot seem to get the return value. I need the value for:
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
and this print out statement:
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
You set subscription equal to 0 and never change it before passing it in to the determineCableSrv method. You do the same with cableSrvs, so the return value from your method is going to be 0. The cableSrvs variable isn't read inside the method, so it probably shouldn't be in input parameter to begin with.
each time the program tries to loop, the error "java.lang.stringindexoutofboundsexception" comes up and highlights
ki=choice.charAt(0);
Does anyone know why that happens?. I'm brand new to programming and this has me stumped. Thanks for any help. Any solution to this problem would be amazing.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k = new Scanner(System.in);
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='W' && ki!='B' && ki!='S')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
choice = k.nextLine();
ki= choice.charAt(0);
switch (ki)
{
case 'W':
{
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
}
}while (ki!='X');
The error means there the index "0" is outside the range of the String. This means the user typed in no input, such as the case when you start the program and hit the enter key. To fix this, simply add the following lines of code:
choice = k.nextLine();
if(choice.size() > 0){
//process the result
}
else{
//ignore the result
}
Let me know if this helps!
As you pointed out, the problem is in:
choice = k.nextLine();
ki= choice.charAt(0);
From the docs nextLine(): "Advances this scanner past the current line and returns the input that was skipped."
So in case the user pressed "enter" the scanner will go to the next line and will return an empty String.
In order to avoid it, simply check if choice is not an empty string:
if (!"".equals(choice)) {
// handle ki
ki= choice.charAt(0);
}
Try this:
Your problem was with the Scanner (k) you need to reset it everytime the loop start over.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k;
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='w' && ki!='b' && ki!='s')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
k= new Scanner(System.in);
choice = k.nextLine();
ki= choice.toLowerCase().charAt(0);
switch (ki)
{
case 'w':
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
if(complete.toLowerCase().equals("y"))
break;
}while (ki!='x');
}
}