Creating Mulitple If statment for Converting height - java

public String convertHeightToFeetInches()
{
int leftOver = heightInInches % IN_PER_FOOT;
if(heightInInches < (IN_PER_FOOT * 2)){
return "1 foot " + leftOver + " inches";
}
else{ return "";
}
if(heightInInches < (IN_PER_FOOT * 3) && heightInInches > (heightInInches * 2)){
return "2 foot " + leftOver + " inches";
}
else{
return "";
}
I want to make it return "1 foot 4 inches" or however tall they are..
I got the first if statment to work but what would i do to continue up to like 6 feet.. I tried just adding another one but im pretty sure thats not how to do it. How can i put this together?

Wouldn't it be simpler just to calculate the foot as well?
public String convertHeightToFeetInches()
{
int inches = heightInInches % IN_PER_FOOT;
int foot = heightInInches / IN_PER_FOOT;
return "" + foot + " foot and " + inches + " inches";
}

It's possible to use a division statement to come up with the number if feet in 'heightInInches'.
Can you try that?
For example, I'm confident that if I know someone is 50 inches tall, I can quickly calculate that the person is at least 4 feet tall.
Once you have that working, we'll work on the inches.

You have most of the logic correct as it is, but you do need a little push. Consider a height between 1 and 2 feet. In mathematical terms, we would describe this as 1 < x <= 2. Consider now what that would translate to in Java - what about x must be true? Hint: it's two conditions.
Next, an if-else if-else won't work if you have an else just sitting there. else will execute if nothing else matches with it (and that will occur often). Place an if after those elses.

Related

WAP in java to input a three digit number and calculate each digit's frequency

I made a program for the question and it's working fine, but in some cases it's not working like when I enter 656, it's showing like this:
The error
The code is showed below:
public static void main(String[] args) {
Scanner rx = new Scanner(System.in);
int ui,uiy,troll3,troll1;
float uix,uis,uiz,uit;
System.out.println("Enter a valid three digit number to calculate the frequency of the digits in it. \n");
ui = rx.nextInt();
if(ui>99&&ui<=999) {
uis = (float) ui;
//System.out.println(uis+" uis");
uix = uis / 10;
//System.out.println(uix+" uix");
uiy = (int) uix;
//System.out.println(uiy+" uiy");
troll3 = (int) ((uix - uiy) * 10); //1st digit
//System.out.println("3d " + troll3);
uiz = uix / 10;
//System.out.println(uiz+ " uiz");
troll1 = (int) uiz;
//System.out.println("1d " + troll1);
uit = (uiz - troll1) * 10;
//System.out.println(uit+" uit");
int troll2 = (int) uit;
//System.out.println("2d " + troll2);
if (troll1 == troll2 && troll1 == troll3) {
System.out.println("The number " + troll1 + " appears three times.");
} else if (troll1 != troll2 && troll2 != troll3 && troll1 != troll3) {
System.out.println("The number " + troll1 + " appears one time.");
System.out.println("The number " + troll2 + " appears one time.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll2) {
System.out.println("The number " + troll1 + " appears two times.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll3) {
System.out.println("The number " + troll3 + " appears two times.");
System.out.println("The number " + troll2 + " appears one time.");
} else if (troll2 == troll3) {
System.out.println("The number " + troll2 + " appears two times.");
System.out.println("The number " + troll1 + " appears one time.");
}
}
else{
System.out.println("The entered number is invalid");
}
}
It mostly gives an error when it consists of digit 5 in the middle. It shows an increment in values and swap in values. Please do help.
Thanks in advance! :-)
Why are you converting to float? float and double attempts to represent an infinite infinity of numbers (there are an infinite amount of integers. Between 2 integers, there are an infinite amount of numbers too: An infinite amount of infinities)... using only 32 bits. This is obviously impossible so instead only a few numbers are representable, and anything else is silently rounded to one of the select few. This means float and double introduce rounding errors.
After any math done to any double or float, == is broken. You can't use those; at best, you can try 'delta equality' (not a == b, but Math.abs(a - b) < 0.00001) but making the claim that your code works for all possible inputs becomes very difficult indeed, it's not going to be very fast, and the code readability isn't great either. So, don't.
Stop using floats, problem solved.
Your 'math' to get the individual digits is a bit circumspect and isn't going to just work if you replace things with int either. What you're missing is the % operator: Module (a.k.a. remainder).
Given, say, 656:
int in = 657;
int digit1 = in % 10;
in = in / 10;
System.out.println(in); // 65
System.out.println(digit1); // 7
int digit2 = in % 10;
in = in / 10;
System.out.println(in); // 6
System.out.println(digit1); // 5
int digit3 = in;

Is there a code on java that allows for two if statements with one independent statement for Shipping Charges?

I am very new to java and have been stuck on a program that I've been trying to create. For background knowledge purposes, the program is for a company called "Ship It" which is a package shipping company. The user enters the weight of the package, and the distance it will travel. Depending on the weight, the company charges a fee per 200 miles.
0 < weight <= 3 pounds $1.00 charge
3 < weight <= 6 pounds $2.00 charge
6 < weight <= 10 pounds $3.00 charge
10 < weight <= 20 pounds $4.00 charge
20 < weight <= 30 pounds $5.00 charge
So far, this is the code I have:
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
//Variables
double costWithoutCharge = 0, weight, distance = 0;
//Introduction to ShipIt
System.out.print("\t\t******Welcome to ShipIt******\n");
System.out.print("***We are a low-charge, secure shipping company for packages" +
"up to 30 pounds***");
//User Enters Weight of Package
System.out.print("\n\nEnter the weight of the package (1.0 - 30.0 pounds): ");
weight = kb.nextDouble();
System.out.print("");
// User Enters distance the package will travel
System.out.print("Enter the miles to the destination (1 - 2000 miles): ");
distance = kb.nextInt();
System.out.print("");
//Weight If-else Statement
if (weight >30.0)
System.out.println ("\nSorry, you have entered invalid data - program terminated");
if (weight >30.0)
System.exit((int) weight);
//Distance Restriction if-else
if (distance >2000)
System.out.println ("\nSorry, you have entered invalid data - program terminated");
if (distance >2000)
System.exit((int) distance);
costWithoutCharge = distance / 200;
//If else
if (weight <0 || weight <=3)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*1.00);
}
else if (weight <3 || weight <= 6)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*2.00);
}
else if (weight <6 || weight <= 10)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*3.00);
}
else if (weight <10 || weight <= 20)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*4.00);
}
else {
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*5.00);
}
kb.close();
}
}
As of now, if I put a value like 1001, the cost to ship is $15.015, but it should be $18 since the charge is multiplied per 200 miles. I am on the fence if I need to do a new equation for the charge per 200 miles dilemma or if it can be supported with another if-statement?
I feel as though I have tried everything but I can't seem to solve this ): I am in dire need of help! Please!
The weight is missing from your example.
it sounds like in your example you have:
distance 1001
weight between 6 and 10, resulting in a $3 charge per "beginning 200 miles"
From your code, 15.015 gets returned.
It appears you want to calculate the "beginning 200 miles", so you could achieve that by rounding up:
costWithoutCharge = Math.ceil( distance / 200 );
On another note, you may want to remove the common parts from your if/then/else block. That is, only perform the calculation but not the System.out.println inside each clause.
First
if (weight <0 || weight <=3)
should be
if (0 < weight && weight <=3)
However the code should be easier to maintain, use a table of limits:
double[][] weightsAndCharges = {
{3, 1.00},
{6, 2.00},
{10, 3.00},
{20, 4.00},
{30, 5.00}
};
double charge = 10.00;
for (double[] weightAndCharge : weightAndCharges) {
if (weight <= weightAndCharge[0]) {
charge = weightAndCharge[1];
break;
}
}
System.out.printf("The cost to ship the package is: $%0.2f%n", charge*distanceRatio);
The answer is some basic math.
What you are thinking of is a combinatorial explosion: If you layer a whole batch of if/elseif statements inside each of your weight if statements for e.g. if (miles < 200) ... else if (miles >= 200 && miles < 400) - then think of it in dimensions: You have the 'miles' dimension which currently is adding 10 options (1-200, 200-399, 400-599, etc), the weight dimension which adds 5.
The amount of ifs you'd need here is then A*B: 50 ifs.
That's a ton, and clearly not what you want.
Math to the rescue!
You really just want to calculate costPerSegment * segments.
Calculate those 2 values individually, and now it's just A + B: 15 ifs. Given that you can actually use math itself to turn the miles number into the # of segments you need to charge (it's just division by 200 for the miles part, no lookup table involved), we're down to 5 ifs.
Note also your code is buggy. Your weight if statement have their > and < reversed. But the else if hides the problem. I fixed that problem in the snippet below.
double costPerSegment;
if (weight <=3) {
costPerSegment = 1.0;
} else if (weight <= 6) {
costPerSegment = 2.0;
} else if (weight <= 10) {
costPerSegment = 3.0;
} else if (weight <= 20) {
costPerSegment = 4.0;
} else {
costPerSegment = 5.0;
}
// Casting a positive double to an int automatically rounds down.
int segments = (int) miles / 200;
double cost = costPerSegment * segments;
This line is causing the problem for input distance 1001
costWithoutCharge = distance / 200; // result = 5,005
As far as I understood you want to have here just 5
So the simpliest solution would be to declare costWithoutCharge as int
and than
costWithoutCharge = (int) distance / 200; // result = 5
Or if you want to keep costWithoutCharge as double you can use Math lib to round it
costWithoutCharge = Math.round(distance / 200); // result = 5

Splitting units base of a number and separating remainders

I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!

Change to number of coins [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to get the minimum amount of coins(quarters, dimes, nickels and pennies) needed to meet a stated amount of change(1-99). Example:
Change: 93
Quarters: 3
Dimes: 1
Nickels: 1
Pennies: 3
When I run my program, I don't get the answers that I'm supposed to. My question is how do I make the output in my program look like the solution above? Do I change the equations within the program to get the numbers I want? The only part of the program I have right is the amount of quarters needed to meet the stated amount. This program also needs to work for ANY stated amount between 1 and 99.
Here's what I have so far:
package mincoins;
import java.util.Scanner;
public class MinCoins2
{
public static void main(String[] args)
{
int change = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
try ( //creates a copy of Scanner class
Scanner in = new Scanner(System.in))
{
System.out.println("Please enter amount of change(1-99)");
change = in.nextInt();
//loop for quarters
while (change >= 25)
{
change = change - 25;
quarters = quarters + 1;
}
while (change >= 10)
{
change = change - 10;
dimes = dimes + 1;
}
while (change >= 5)
{
change = change - 5;
nickels = nickels + 1;
}
pennies = change;
System.out.println("Change: " + change);
System.out.println("Quarters = " + change);
System.out.println("Dimes = " + change);
System.out.println("Nickels = " + change);
System.out.println("Pennies = " + change);
}
}//end of main
}//end of class
You have typos on the last 4 lines:
System.out.println("Change:" + change);
System.out.println("Quarters= "+ change);
System.out.println("Dimes=" + change);
System.out.println("Nickels=" + change);
System.out.println("Pennies=" + change);
Are all printing change
Also, the while loop conditions should be >= instead of >.
Lastly, to print out the change at the end, you have to copy it, since you're modifying it in your while loops.
change = in.nextInt();
int changeOut = change;
...
System.out.println("Change:" + changeOut);
Live Demo
Obviously the typo is the problem, needs to be:
System.out.println("Quarters = " + quarters);
System.out.println("Dimes = " + dimes);
System.out.println("Nickels = " + nickles);
System.out.println("Pennies = " + change);
But I want to make a suggestion about how this code works W.R.T. to the loops, e.g.:
//loop for quarters
while (change > 25) {
change = change - 25;
quarters = quarters + 1;
}
This is easily done without a loop:
quarters = change / 25;
change = change - quarters * 25;
This is because change and 25 are ints, so / will do an integer division. It will give the largest number of quarters that fit in the change, i.e. it's rounding down.
Going one step further you can also use the % modulo operator to get the remaining change at each step:
quarters = change / 25;
change = change % 25;
dimes = change / 10;
change = change % 10;
nickels = change / 5;
change = change % 5;
The main problem is the variables you're using. You should be using your quarters, dimes, nickels, and pennies variables in the appropriate spots.
There's another logical error - you need to exhaust all of the leftover change to comprise your pennies count. Since your output (the one you actually require) doesn't mandate that you count the change left over (since it should be 0), you can avoid another loop altogether and just directly assign pennies to change:
pennies = change;
...and this will give you the right result for the total number of pennies left over.
As some general cleanup, you would also want to avoid assigning in the print statement, as it can be a bit confusing. Use statements such as change -= 25 independent of the System.out.println instead.

No if-else branch is entered on certain values

I am have a little trouble with this java homework. I am still fairly new to this programming work. I am having trouble making the program do the following: Scientists measure an object’s mass in kilograms and its weight in Newtons. If you know the amount of mass that an object has, you can calculate its weight, in Newtons, with the following formula:
Weight = mass X 9.8
Write a program that asks the user to enter an object’s mass, and then calculate its weight. If the object weighs more than 1000 Newtons, display a message indicating that it is too heavy. If the object weighs less than 10 Newtons, display a message indicating that the object is too light.
this is what I have written so far:
import java.util.Scanner;
public class MassandWeight{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double mass;
System.out.print("Please enter the object's mass: ");
mass = keyboard.nextDouble();
// Convert the mass to weight using the following expression:
double weight = (mass * 9.8);
if (weight >= 10 && weight <= 1000)
System.out.println("The weight of the object is " + weight + ".");
else if (weight > 1001)
System.out.println("The object's weight is too heavy.");
else if (weight < 9)
System.out.println("The object's weight is too light.");
}
}
so everything works great! and I am really proud of myself for getting this far. however when I enter "1" i get no response back. everything else works great. if you need more information, please let me know. Thank you!!
You're checking for values of weight in (-∞, 9), [10, 1000] and (1001, +∞). This means that you're missing values in [9 and 10) and (1000, 1001]. If you input 1, the weight will be 9.8 and you'll be missing it.
Here's what your ifs should look like, instead:
if (weight >=10 && weight <= 1000) ...
else if (weight > 1000) ...
else if (weight < 10) ...
Since it's for a homework, I won't give it all out... but check your if/else... maybe put an else at the end so you can see the scenarios that are not caught with your else if.
When you enter 1 then the weight = (1* 9.8) = 9.8
you have 3 conditions:
1- weight >=10 && weight <= 1000
2- weight > 1001
3- weight < 9
so 9.8 doesn't match with this conditions
you need else {} at the end
Check the last else statement. It does not check if it is less than 10. When the weight is > 9 && < 10, no statement is executed (entering 1 sets the weight to 9.8)
I write else-if statements like this in ways that guarantee an execution of a path. Consider the following:
if (weight < 10) {
// too light
} else if (weight > 1000) {
// too heavy
} else {
// just right - this MUST be the case if
// the previous branches are not selected
}
Using an approach like this helps me reduce programming bugs and increase refactorability by removing duplication of comparissions. I also find it easier to read.
See TDWTF: But...Anything Can Happen! for an extreme perversion of duplicating comparisons: the posted code isn't nearly as bad, but in my opinion it suffers from the same fundamental flaw.
You have to change
else if (weight < 9)
to
else if (weight < 10)
and
else if (weight > 1001)
to
else if (weight > 1000)

Categories