I have the following code (I'm not very computer literate so be gentle) that the user is supposed to be able to enter individual coin amounts and the program will tell the user how much money they have in said coin amounts.
import java.util.*;
public class Coins {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
System.out.println ("Lab 2 by Maria T Williams\n");
quarterAmount( );
dimeAmount( );
nickelAmount( );
pennyAmount( );
}
public static void quarterAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterNumber = CONSOLE.nextInt( );
double amount = quarterNumber * 0.25;
System.out.print(quarterNumber + " You have $" + amount);
System.out.println(" worth of quarters.");
}
public static void dimeAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeNumber = CONSOLE.nextInt( );
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + amount);
System.out.println(" worth of dimes.");
}
public static void nickelAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelNumber = CONSOLE.nextInt( );
double amount = nickelNumber * 0.05;
System.out.print(nickelNumber + " You have $" + amount);
System.out.println(" worth of nickels.");
}
public static void pennyAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyNumber = CONSOLE.nextInt( );
double amount = pennyNumber * 0.01;
System.out.print(pennyNumber + " You have $" + amount);
System.out.println(" worth of pennies.");
}
}
If I enter an amount that has a number in the 100s place that isn't "0" I'm fine. But if I enter, say, two quarters I get back "$0.5" instead of "$0.50".
You could use a DecimalFormat to force the number to be formatted as you'd like it. E.g.:
DecimalFormat df = new DecimalFormat("#.00");
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + df.format(amount) + " worth of dimes.");
When outputting the result of your calculation, you can use a DecimalFormat like this:
DecimalFormat f = new DecimalFormat("#0.00");
System.out.println(f.format(dimeNumber));
Related
I am trying get an output from this code. It will compile and return perfectly, but as soon as I add the final " calories" string at the end I will get an error message. Literally having the " calories" at the end of the output is the difference between my code running and not. I am sorry if I worded this weird this is my first time seeking help on a platform like this.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int age;
int weight ;
int bpm;
int min;
double calories1;
age = scnr.nextInt();
weight = scnr.nextInt();
bpm = scnr.nextInt();
min = scnr.nextInt();
calories1 = ( (age * 0.2757) + (weight * 0.03295) + (bpm * 1.0781) - 75.4991) * min / 8.368 ;
System.out.printf("Calories: " + "%.2f",calories1 + " calories");
}
}
You'll have to format double calorie1 to a string to print double upto two decimal places
System.out.printf("Calories: " + String.format("%.2f", calories1) + " calories");
I am a complete beginner with java and coding altogether and am trying to make a program that solves two equations based on what a user has inputted into the program. I've tried changing the variable types to long, int, double, but nothing changes. The result is always 0 or 0.0 Any help would be much appreciated.
package pa2;
import java.util.Scanner;
public class GravitationalForce
{
public static void main(String[] args)
{
System.out.println("Please enter the name of the planet and its weight in quintillion kilograms");
Scanner myScanner = new Scanner (System.in);
String planetName = myScanner.next();
int planetWeight = myScanner.nextInt();
System.out.println("Enter the weight of the person in kilograms");
double personWeight = myScanner.nextDouble();
System.out.println("Please enter the radius of the planet Alderaan in million meters");
double planetRadius = myScanner.nextDouble();
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
Double force = gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6);
Double gravity = gravitationalConstant*(planetWeight*Math.pow(10, 18)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6));
System.out.println("The gravitational force of planet " + planetName + " on the person is " + force + " Newtons");
System.out.println("The gravity of the planet " + planetName + " is " + gravity + " meters per second squared");
}
}
6.673*Math.pow(10,-11) is < 1, so if you cast it to long, it becomes 0.
change
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
to
double gravitationalConstant = 6.673*Math.pow(10,-11);
I have to do this program where I have to display the calculation of the profit for each individual stock, but I also have to display the profit for the total amount of stocks. My code only has it so it displays the calculation for all of the stocks:
import java.util.Scanner;
public class KNW_MultipleStockSales
{
//This method will perform the calculations
public static double calculator(double numberShare, double purchasePrice,
double purchaseCommission, double salePrice,
double salesCommission)
{
double profit = (((numberShare * salePrice)-salesCommission) -
((numberShare * purchasePrice) + purchaseCommission));
return profit;
}
//This is where we ask the questions
public static void main(String[] args)
{
//Declare variables
Scanner scanner = new Scanner(System.in);
int stock;
double numberShare;
double purchasePrice;
double purchaseCommission;
double salePrice;
double saleCommission;
double profit;
double total = 0;
//Ask the questions
System.out.println("Enter the stocks you have: ");
stock = scanner.nextInt();
//For loop for the number stock they are in
for(int numberStocks=1; numberStocks<=stock; numberStocks++)
{
System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
numberShare = scanner.nextDouble();
System.out.println("Enter the purchase price" + numberStocks + ": ");
purchasePrice = scanner.nextDouble();
System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
purchaseCommission = scanner.nextDouble();
System.out.println("Enter the sale price:" + numberStocks + ": ");
salePrice = scanner.nextDouble();
System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
saleCommission = scanner.nextDouble();
profit = calculator(numberShare, purchasePrice, purchaseCommission,
salePrice, saleCommission);
total = total + profit;
}
//Return if the user made profit or loss
if(total<0)
{
System.out.printf("You made a loss of:$%.2f", total);
}
else if(total>0)
{
System.out.printf("You made a profit of:$%.2f", total);
}
else
{
System.out.println("You made no profit or loss.");
}
}
}
How can I get it so each individual stock profit gets shown, with the profit of all the stocks together?
Try maintaining a separate Map for profit/loss. You may want to accept Stock Name as an input which will help manage individual stocks effectively.
// Map of stock name and profit/loss
Map<String,Double> profitMap = new HashMap<String,Double>();
After calculating profit/loss, add entry to map
profitMap.put("stockName", profit);
total = total + profit;
At the end of your program, iterate and display profit/loss for each Stock from Map.
for (Entry<String, Integer> entry : profitMap.entrySet()) {
System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
}
This code doesn't work. I get the following errors (in eclipse) that I can't seem to resolve:
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
Syntax error, insert ";" to complete BlockStatements
Duplicate local variable interest
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("input: ");
String input = in.next();
Integer interest = null; //to define interest
do
{
double interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
};
}
The variable interest is declared twice.
Here is a slightly cleaned up version of your code:
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("press 'N' to exit");
String input = in.next();
double interest = 0; //to define interest
do
{
interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
}
}
I'm writing this program that will let you enter in an amount for each quarters, dimes, nickels and pennies and return their amount in $. After that, I want to be able to add up the dollar amounts they produce without having to enter in all of the coin amounts a second time. Any ideas? Thanks in advance.
import java.util.*;
public class HalfDollar {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
quarterDollarAmount( );
dimeDollarAmount( );
nickelDollarAmount( );
pennyDollarAmount( );
totalDollarAmount( );
}
public static double quarterDollarAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterDollar = CONSOLE.nextInt( );
double amount = quarterDollar * 0.25;
System.out.println(quarterDollar + " Quarter are $" + amount);
return amount;
}
public static double dimeDollarAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeDollar = CONSOLE.nextInt( );
double amount = dimeDollar * 0.10;
System.out.println(dimeDollar + " Dimes are $" + amount);
return amount;
}
public static double nickelDollarAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelDollar = CONSOLE.nextInt( );
double amount = nickelDollar * 0.05;
System.out.println(nickelDollar + " Nickels are $" + amount);
return amount;
}
public static double pennyDollarAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyDollar = CONSOLE.nextInt( );
double amount = pennyDollar * 0.01;
System.out.println(pennyDollar + " Pennies are $" + amount);
return amount;
}
public static double totalDollarAmount( ) {
double quarter = quarterDollarAmount();
double dime = dimeDollarAmount();
double nickel = nickelDollarAmount();
double penny = pennyDollarAmount();
double total = quarter + dime + nickel + penny;
System.out.println("Total amount is $" + total);
return total;
}
}
Hmmm, this smells to me like a homework problem. If you are truly the one who wrote this code, any number of solutions should be pretty obvious. But whatever, I won't judge your journey. Since you are returning the amount from each method, just keep a running total of all the amounts as you go along, then change your totalDollarAmount method to take the total as input instead of asking for it again:
double total = 0.0;
total += quarterDollarAmount( );
total += dimeDollarAmount( );
total += nickelDollarAmount( );
total += pennyDollarAmount( );
totalDollarAmount( total );
You're not doing anything with your variables. Just calling them and then they're moving out of scope.
You could either store the returned value in a global variable to use later.
private double quarter, dime, total;
public static void main(String[] args) {
quarter = quarterDollarAmount();
dime = dimeDollarAmount();
total = (quarter + dime);
s.o.p(total);
}
If you don't care about the value after printing it out you can either total them up with local variables or literally just total up your methods as follows.
public static void main(String[] args) {
s.o.p(quarterDollarAmount( ) + dimeDollarAmount( ) + ....);
}
To get your value to 2 decimal places use something like the following:
DecimalFormat format = new DecimalFormat("#.00");
Double total_formatted = Double.parseDouble(format.format(total));
s.o.p(total_formatted);
That enforces the value to have 2 decimal places with an optional amount of digits left of the decimal place.
Final thing, you probably don't want to make everything static. It basically defeats the point of object orientation as static variable will persist throughout all objects of a class.