Program that lists amount of weight in a given input - java

I am attempting to write a program that will list the amount of kilograms, grams, and milligrams in a given input. Ex. in the given input of 1050042mg, the output will say that there is 1 kilogram, 50 grams, and 42 milligrams.
import java.util.Scanner;
class milligrams {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int milligram;
double kilo, gram;
System.out.println("Enter the weight in milligrams: ");
milligram = in.nextInt();
kilo = milligram / 1000000;
gram = milligram / 10000;
milligram = milligram / 1;
System.out.println("The weight is " + kilo + "kilos, " + gram + "grams" + milligram + " milligrams");
}
}
The part I am struggling with is I believe I must change the 10-12 lines with code that will read the given user input and then divide the input by the appropriate number to get kg, g, and mg but I cannot figure out how to do it as I am new to java. I am aware the division numbers are incorrect but I don't believe that is the issue. If this is not the right approach please guide me to the right approach.

You can use the modulus (clock arithmetic) operator
const KG = 1000000;
const GRAM = 1000;
Scanner in = new Scanner(System.in);
int milligram;
double kilo, gram;
System.out.println("Enter the weight in milligrams: ");
milligram = in.nextInt();
kilo = milligram / KG;
//use the modulus here (and below)
milligram = milligram % KG;
gram = milligram / GRAM;
// 2nd use of modulus, this time with GRAN
milligram = milligram % GRAM;
System.out.println("The weight is " + kilo + "kilos, " + gram + "grams" + milligram + " milligrams");
}

Related

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Program will not do calculations

int single = 0, doub=0, triple=0, homer=0, atbats=0, totalbase, totalhits;
double slug, battingavg;
Scanner sc = new Scanner(System.in);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
while (single != -1)
{
System.out.print("Enter doubles: ");
doub = sc.nextInt();
System.out.print("Enter triples: ");
triple = sc.nextInt();
System.out.print("Enter home runs: ");
homer = sc.nextInt();
System.out.print("Enter total at bats: ");
atbats = sc.nextInt();
System.out.print("Enter the player's name: ");
String name = sc.next();
totalbase = (single + doub * 2 + triple * 3 + homer * 4);
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
System.out.println("Player's name is " + name);
System.out.printf("The slugging percentage is %.3f\n", + slug);
System.out.printf("The batting percentage is %.3f\n", + battingavg);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
}
This program will only output a 1 or a 0 after the calculations. Everything else works fine, but It just doesn't seem to do the calculations.
The problem is that when you do integer divisions, you'll get integer values. Instead use double or float data types. I see slug and battingavg are already doubles, but you're assigning the result of an integer division to them. If you cast at least one of the values in your calculations to a double you should get the output you expect. Example:
slug = totalbase / (double) atbats;
battingavg = (single + doub + triple + homer) / (double) atbats;
When you divide integer values and store the result in a double that is a widening conversion, but the value was calculate as an integer and thus you're widening the integer value.
Change this,
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
to something like this,
slug = ((double) totalbase / atbats);
battingavg = ((double) (single + doub + triple + homer) / atbats);
to get double values into your double variables.

modulus and int for note calculations

Java input;
import java.util.*;
public class NetPay3
{
public static void main()
{
// Define Scanner object
Scanner inLine = new Scanner (System.in);
// Define other variables
float pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds,
OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
// Ask for the time in seconds
System.out.print ("Enter Net Pay : ");
pay = inLine.nextFloat();
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OneHundredPounds = (int) pay / 100;
// Calculate what is left over and store back into seconds
pay = pay % 100;
// Calculate the minutes. There are 60 seconds
// in a minute.
FiftyPounds = (int) pay / 50;
// Whatever is left over must be the seconds
pay = pay % 50;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
TwentyPounds = (int) pay / 20;
// Calculate what is left over and store back into seconds
pay = pay % 20;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FivePounds = (int) pay / 5;
// Calculate what is left over and store back into seconds
pay = pay % 5;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OnePound = (int) pay / 1;
// Calculate what is left over and store back into seconds
pay = pay % 1;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FiftyPence = (int) pay / 2;
// Calculate what is left over and store back into seconds
pay = pay % 2;
// Display the hours, minutes and seconds
System.out.println ("Amount of £100 notes " + OneHundredPounds);
System.out.println ("Amount of £50 notes " + FiftyPounds);
System.out.println ("Amount of £20 notes " + TwentyPounds);
System.out.println ("Amount of £5 notes " + FivePounds);
System.out.println ("Amount of £1 coins " + OnePound);
System.out.println ("Amount of 50p coins " + FiftyPence);
}
}
Screen input and output;
Enter Net Pay : 176.50
Amount of £100 notes 1
Amount of £50 notes 1
Amount of £20 notes 1
Amount of £5 notes 1
Amount of £1 coins 1
Amount of 50p coins 0
Hi relatively new to programming,
having trouble with me modulus and int operators in terms of getting them to function with the correct output on screen, previous syntax's worked correctly bar the 50p, anyone care to shed any light? thanks :)
Try changing FiftyPence = (int) pay / 2; toFiftyPence = (int) (pay / 0.5f);
Here is your code corrected and improved.
Don't use floats here, use integer arithmetic.
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
// Define Scanner object
Scanner inLine = new Scanner(System.in);
// Define other variables
int pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds, OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
OneHundredPounds = (int) pay / 10000;
pay = pay % 10000;
FiftyPounds = (int) pay / 5000;
pay = pay % 5000;
TwentyPounds = (int) pay / 2000;
pay = pay % 2000;
FivePounds = (int) pay / 500;
pay = pay % 500;
OnePound = (int) pay / 100;
pay = pay % 100;
FiftyPence = (int) pay / 50;
pay = pay % 50;
System.out.println("Amount of £100 notes " + OneHundredPounds);
System.out.println("Amount of £50 notes " + FiftyPounds);
System.out.println("Amount of £20 notes " + TwentyPounds);
System.out.println("Amount of £5 notes " + FivePounds);
System.out.println("Amount of £1 coins " + OnePound);
System.out.println("Amount of 50p coins " + FiftyPence);
System.out.println("Leftover pence: " + pay);
}
}
But I would further simplify this to (for example) this program:
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
Scanner inLine = new Scanner(System.in);
float[] val = new float[]{100, 50, 20, 5, 1, 0.5f, 0.2f, 0.05f, 0.02f, 0.01f};
int pay;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
for (int i=0; i<val.length; i++){
int m = ((int)(val[i] * 100));
int cnt = pay / m;
String s1 = val[i] < 1 ? " coins: " : " notes: ";
String s2 = val[i] < 1 ? "" : "£";
String s3 = val[i] < 1 ? "p" : "";
String s4 = val[i] < 1 ? m + "" : (m/100) + "";
System.out.println("Amount of " + s2 + s4 + s3 + s1 + cnt);
pay = pay % m;
}
}
}

Converting from Double to Binary

I've been a lot of trouble figuring this class problem. My due date is tomorrow and I still don't know how to do it. I made a code when the input put by the user is converted into binary, octal, and hexadecimal. Now, the problem is that now they are asking me to modify the code in a way that the user inputs a Double or Floating point and convert it into decimal. My greatest problem is working with the decimal numbers; for example, 5*.987*. I will leave the code I already created. I would be very grateful is someone could help! thanks :)
import java.util.Scanner;
class EncodingTester {
public static void main(String args[]) {
byte largestPositiveByte = 127;
short largestPositiveShort = 32767;
int largestPositiveInt = 2147483647;
long largestPositiveLong = 9223372036854775807L;
long largestPositiveLongPlusOne = 9223372036854775807L;
Scanner in = new Scanner(System.in);
System.out.println("Next number (0 to stop): ");
long nextNumber = in.nextLong();
while (nextNumber != 0) {
int radix;
double logBase2 = Math.log(nextNumber) / Math.log(2);
double absoluteNumOfBits = 1 + Math.floor(logBase2);
double maxBits = Math.max(8, absoluteNumOfBits);
double numBits = Math.log(maxBits) / Math.log(2);
int newNumBits = (int) Math.pow(2, Math.ceil(numBits));
System.out.println("The absolute number of bits is: " +absoluteNumOfBits +". The final number of bits is: " +newNumBits +".");
radix = 10;
System.out.println("Decimal: " + String.format("%s", Double.toString(nextNumber)).replace(' ','0'));
radix = 2;
System.out.println("Binary: " + String.format("%"+newNumBits+"s", Long.toString(nextNumber,radix)).replace(' ','0'));
radix = 8;
System.out.println("Octal: " + String.format("%"+((int) Math.ceil(newNumBits/3.0))+"s", Long.toString(nextNumber,radix)).replace(' ','0'));
radix = 16;
System.out.println("Hexadecimal: 0x" + String.format("%"+newNumBits/4+"s", Long.toString(nextNumber,radix)).replace(' ','0'));
System.out.println("");
System.out.println("Next number: (0 to stop)");
nextNumber = in.nextLong();
}
System.out.println("Good Bye");
}
}

Change Machine Math & Logic Errors

I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?

Categories

Resources