Adding a list of user-inputted doubles to an Array - java

So my program, when instantiated asks the user how many "items" they want. My program then creates two arrays, one for the "item name" and one for the "item price". I use a loop to let the user input each item name and item price in their respective arrays, however I'm lost with the item price array. To use my loop, I need to utilize the "itemprice.length" element but I can't do that when I'm not working with Strings.
After the user inputs the "prices" of each item, I need to apply a multiplier to each array item and output it. So I want to, for example, have 3 items in the array: 1.20, 1.30, 1.40, and then I want the program to ask me for the "sales tax" of which I can enter 0.08 and it will then multiply 0.08 to each item and output a total.
Is there a way that I can make my program work so it allows the user to enter, let's say, 5 items and their prices and am I going about it the right way? Any way of doing this easier? Thanks!
public class Input
{
private Scanner keybd;
private String item;
private double cost;
private String[] costArray;
private String[] itemArray;
/**
* Constructor for objects of class Scanner
*/
public Input(int anyAmountofItems)
{
keybd = new Scanner(System.in);
costArray = new String[anyAmountofItems];
itemArray = new String[anyAmountofItems];
}
/**
* Mutator method to set the item names and costs
*/
public void setArray(){
for(int index=0; index < itemArray.length; index++){
System.out.println("Enter the item name: ");
itemArray[index] = keybd.next();}
for(int indexa=0; indexa < itemArray.length; indexa++){
System.out.println(itemArray[indexa]);
}
for(int indexb=0; indexb < costArray.length; indexb++){
System.out.println("Enter the item cost: ");
costArray[indexb] = keybd.next();}
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println(costArray[indexc]);
}
}
/**
* Accessor method to return the items cost with tax
*/
public double getTax(){
return costArray.length;
}

Use a Float[] and use Float.parseFloat(String str) to convert from a string to a float.
As an aside, when dealing with money, floating point is a bad idea, since there are always issues with precision. It is best to use ints/longs with the appropriate lowest currency unit (i.e cents in the US etc.)

you can try as:
System.out.println("Enter the sales tax: ");
double salesTax = keybd.next();
double totalTax =0.0;
double total = 0.0;
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println("Enter the item cost: ");
double cost = Double.valueOf(keybd.next()).doubleValue();
totalTax = totalTax + (cost * salesTax);
total = total + cost;
}
System.out.println("Total: " + (total-totalTax));
EDIT: TO calculate the total during inserting the cost.

It's not clear to me what your question is. Are you having problems with the item cost data? You are just reading in a String. You should read in an array of doubles instead.
costArray = new double[anyAmountOfItems];
// Then when reading use the appropriate Scanner method
costArray[indexb] = keybd.nextDouble();
A couple style notes:
You might want to consider using Lists instead of arrays. That way you don't have to worry about fixing the size of the arrays.
There is no need to use new variable names in each of the for loops. It just adds confusion. Instead of indexa, indexb, etc just use i.
Better yet, use the enhanced for loop for cases where you don't really need the index:
for( String item : itemArray ) {
System.out.println(item);
}

Related

how do i delete variables in order to reuse them in java

I am making a calculator that theoretically should be able to go over the normal integer limit right now I am prototyping a smaller test version of this thing. I often have to often carry a number like in multiplication but I use the same variable over and over again and I want to be able to clear those variables in order to reuse them in my calculator
import java.util.Scanner;
import java.util.LinkedList ;
public class mass_mulitplication_software {
public static void multiply () {
Scanner keyboard = new Scanner (System.in);
//multiplication#1
System.out.println("ones place");
double fnum1 = keyboard.nextDouble() ;
System.out.println("tens place");
double fnum2 = keyboard.nextDouble() ;
System.out.println("hundreds place");
double fnum3 = keyboard.nextDouble() ;
//multiplication#2
System.out.println("ones place");
double snum1 = keyboard.nextDouble() ;
System.out.println("tens place");
double snum2 = keyboard.nextDouble() ;
System.out.println("hundreds place");
double snum3 = keyboard.nextDouble() ;
tnum=fnum1*snum1;
mass_mulitplication_software.carry();
tnum=fnum1*snum2;
mass_mulitplication_software.carry();
tnum=fnum1*snum3;
mass_mulitplication_software.carry();
tnum=fnum2*snum1;
mass_mulitplication_software.carry();
tnum=fnum2*snum2;
mass_mulitplication_software.carry();
tnum=fnum2*snum3;
mass_mulitplication_software.carry();
tnum=fnum3*snum1;
mass_mulitplication_software.carry();
tnum=fnum3*snum2;
mass_mulitplication_software.carry();
tnum=fnum3*snum3;
}
public static double carry(){
if (tnum>10){
double mnum= tnum%10;
double mmnum = tnum- mnum ;
double cnum = mmnum/10 ;
return cnum;}
public static void main(String[] args) {
mass_mulitplication_software.multiply();
} }
also please consider I am a novice coder who has just begun coding and wished to improve upon my old calculator to take bigger numbers this a small version prototype for multiplying specifically do any of u guys know how to clear a double variable so it can be reused with a different #
As previous commentor's said consider using BigInteger or unsigned int. And put each input into its own variable, it will make your life a lot easier, and you wont need the carry() method.
Aside from that, a few things to point out, you call the carry() method, but do nothing with the double that it returns, also in this case, tnum will always equal fnum3 * snum3
You could always make a menu with an option to clear all numbers, and upon choosing that option, have a method that sets those variables to 0. This menu would go in the main method.
It seems like you might want to have a menu using a while loop regardless, so you can repeat this process over and over again with different values.
something like:
int menuChoice = -1;
while (menuChoice < 1 || menuChoice > 8) {
System.out.println();
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Power");
System.out.println("6. Logarithm");
System.out.println("7. Clear");
System.out.println("8. Quit");
System.out.println();
System.out.print("What would you like to do? ");
menuChoice = input.nextInt();
if (menuChoice < 1 || menuChoice > 8) {
System.out.println(menuChoice + " wasn't one of the options");
}
}
return menuChoice;
}
This is the menu from a calculator I'm working on. You can use if statements to perform appropriate functions based on what the user enters. So you could have a menu option to multiply, and have the user enter values into each variable for your numbers.
You don't actually have to clear variables--after a function is performed, the menu would simply display again after the operation is performed, since menuChoice is initialized to -1 before the while loop. The user would just choose an option and enter new values into those variables which would replace the old ones.
You might simply want to use unsigned long long int as your variable type, since it's range is from 0 to 18,446,744,073,709,551,615. The method you're using seems overly complicated.
You might consider using an array to store the digits of your variables, rather than trying to hold all the digits in individual variables. This will make it easier for you to iterate over them when you do your carry() and borrow() operations, since those may need to move values up and down the length of your digits.
You could then, say, do multiplication and division the way you would long-hand, using an array to store intermediate values. Consider:
public class Digits {
List<Integer> digits;
public Digits() {
digits = new ArrayList<>();
}
public Digits(Digits other) {
digits = other.getDigits();
}
public List<Integer> getDigits() {
return digits;
}
public Digits times(Digits other) {
List<Integer> newDigits = new ArrayList<>();
for (int i=0; i<other.getDigits().size(); i++) {
for (int j=0; j< digits.size(); j++) {
Integer temp;
try {
temp = newDigits.get(i+j);
} catch (IndexOutOfBoundsException ioobe) {
temp = 0;
}
newDigits.set(i+j, temp + other.getDigits().get(i) * digits.get(j));
}
carry();
}
}
private void carry() {
for (int i=0; i<digits.size(); i++) {
while (digits.get(i) >= 10) {
digits.set(i, digits.get(i) - 10);
digits.set(i+1, digits.get(i+1) + 1);
}
}
}
}

How to save the double variables on an array in java?

Good day! I am trying to make a program that will ask the user to input the total number of the items. After the input of the total items, the program should ask the price of each item, based on the input. After the input of the prices, the program should compute the total price and ask for the cash. If the cash is not sufficient to pay the items, allow the user to re-enter cash until he/she inputted enough to pay the bill. Lastly, it will print the change of the user.
My problem is, how to I compute the price of each item. I think I need an array to save each prices and compute them afterwards. Here is my program, I know its a mess, sorry im still a beginner. Hoping for a solution. Thank you so much!!
public class Store {
public static void main(String[] args) {
Scanner v = new Scanner (System.in);
int totalitems;
int change;
int cash;
double price[];
double totalprice;
System.out.print("Enter Total Number of Items: ");
totalitems = v.nextInt();
for(int loop=1; loop<=totalitems; loop++) {
System.out.print("Enter the price of each item: ");
price[totalitems] = v.nextInt();
}
//i need a solution here for array
System.out.print("Enter the your cash: ");
cash = v.nextInt();
if(cash < totalprice) {
System.out.print("Please input a sufficient amount: ");
cash = v.nextInt();
}else {
change = cash - totalprice;
}
System.out.print("Thank you! Your change is: " + change);
}
}
You can iterate over the price array, either in the old-fashioned way:
for(int loop=0; loop < totalitems; loop++) {
totalPrice = totalPrice + price[loop];
}
or, in the new way:
for (double itemPrice : price) {
totalPrice = totalPrice + itemPrice;
}
But you're forgetting something else as well: the price[] array isn't initialized. As soon as the totalItems is known, you must do
price[] = new double[totalItems];
Otherwise Java wouldn't know how much memory to reserve for the array.

Generate and distribute random numbers fairly in java

Hi I have been trying to figure this quiz out
A lottery company shares out prizes to winning contestants every week. Most weeks, more than one contestant wins, in which case they try to share out the prizes as fairly as possible. Their prize distribution office has hired you to write a program that they will use to distribute prizes in the fairest way possible.
The program you write should take two lines of input:
A comma-separated list of this week's prizes' values
A comma-separated names of this week's winners
For example, the input could be:
100,800,200,500,400,1000
Joshua,Mahesh,Lilian
The program should then output the fairest possible distribution of prizes, by displaying one line for each winner, with the values of the prizes allocated to them. For example, given the input above, the output could be:
Joshua:100,400,500
Mahesh:1000
Lilian:800,200
The example above gives a perfect solution, where all winners get the same value of prizes (total value of 1000 each). In many cases, this will not be possible, but all prizes must be distributed and cannot be divided. Part of your job is to decide how you define 'fair' for these cases. For example, given the input
400,400,500,600
Barry,Sheila,Onyango,Wekesa
The following would be acceptable output, because there is no fairer distribution possible:
Barry:400
Sheila:400
Onyango:500
Wekesa:600
I am using java and so far this is what I have come up with
import java.util.Scanner;
import java.util.Arrays;
public class Main {
private static String amounts;
private static String names;
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print(
"Please enter the lottery amounts separated by commas: ");
if (userInput.hasNext()) {
amounts = userInput.next();
// System.out.println("You entered: " + amounts);
}
System.out.print("Please enter the contestants names: ");
if (userInput.hasNext()) {
names = userInput.next();
// System.out.println("You entered: " + names);
}
String amountArray[] = amounts.split(",");
String nameArray[] = names.split(",");
award(nameArray, amountArray);
}
// Method that awards the amounts to the winners
public static void award(String names[], String amounts[]) {
int randomAmount;
int randomName;
for (int i = 0; i < amounts.length; i++) {
randomAmount = (int) (Math.random() * amounts.length);
int usedValue[] = new int[amounts.length];
usedValue[i] = randomAmount;
if (checkValueUsed(randomAmount, usedValue)) {
randomName = (int) (Math.random() * names.length);
int usedName[] = new int[names.length];
System.out.println(names[randomName] + " = "
+ amounts[randomAmount]);
} else {
break;
}
}
}
private static boolean checkValueUsed(int currentState, int[] myArray) {
boolean found = false;
for (int i = 0; !found && (i < myArray.length); i++) {
if (myArray[i] == currentState) {
found = true;
}
}
return found;
}
private void checkUsedValue(int currentState, int[] myArray) {
for (int i = 0; (i < myArray.length); i++) {
if (myArray[i] == currentState) {
}
}
}
}
My idea of fair is to select a random amount and assign it to a random winner.
1) This looks like an interview/exam question. I'm not to judge but... really?
2) Your idea of fair is NOT what is intended. By the examples given, fair means all prizes are distributed and each winners total is as close to each other as possible.
3) From the above - this is a known problem. A greedy algorithm is likely to perform well. (I can't really see why not, unless you get very specific on the optimization part of the problem)
For a "fair" distribution you could try something like this:
Randomly order the winners.
For each winner, assign them the current highest available prize; so using your first example, winner one gets 1000, winner two gets 800, winner three gets 500.
If there are prizes left to distribute, for all but the first winner, assign them the current highest available prize that doesn't take them above the prize total of the first winner; winner two would get 200 (matching the 1000 of winner one), winner three gets 400 (to make 900).
Repeat step three until there are no more prizes or no prizes have been allocated; winner three gets 100 to match the 1000 of the other two.
If there are still prizes to allocate, sort the winners in descending order based on total prizes, and start allocating the lowest available prizes to all but the first winner.
Repeat step five until all prizes are allocated.

Java JOptionPane Output

Can anybody tell me what I am doing wrong here. I need to calculate some values from user-input into some JOptionPane-input-dialog-boxes, then outputting the answers.
I would greatly appreciate any help I get. Thanks In Advance!
Input
Number of loans to compare (Could be more than 1)
Selling price
Down payment
You will ask the following for each loan they want to compare
Interest rate
Number of years
Processing
You will need to calculate the monthly payment for each scenario listed in part d for the given interest rates and number of years.
Output
Selling price
Down Payment
Loan Amount
List for each scenario
interest
years
payment
Here's my code so far:
package javamortgagecalculator;
import javax.swing.JOptionPane;
import java.util.*;
public class JavaMortgageCalculator {
public static void main(String[] args) {
//A. Enter the Number Of Loans to compare
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
//Convert numberOfLoansString to int
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
//Convert homeCostString to double
double sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
double downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
double loanAmount = sellingPrice - downPayment;
//D. Ask the following for as many number of loans they wish to compare
//D1 Get the interest rate
double[] annualInterestRatesArray = new double[numberOfLoans];
double[] monthlyInterestRateArray = new double[numberOfLoans];
int[] numberOfYearsArray = new int[numberOfLoans];
double[] monthlyPaymentArray = new double[numberOfLoans];
double[] totalPaymentArray = new double[numberOfLoans];
int counter = 1;
for (int i=0; i < numberOfLoans; i++)
{
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
double annualInterestRate = Double.parseDouble(annualInterestRateString);
annualInterestRatesArray[i] = (annualInterestRate);
//Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
monthlyInterestRateArray[i] = (monthlyInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
int numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArray[i] = (numberOfYears);
//Calculate monthly payment
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPaymentArray[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
//Format to keep totalPayment two digits after the decimal point
totalPayment = (int)(totalPayment * 100) / 100.0;
totalPaymentArray[i] = (totalPayment);
counter++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numberOfLoans; i++) {
sb.append(String.format("\t \t \t \t \t \n", sellingPrice, downPayment, loanAmount, Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray)));
}
String toDisplay=sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
If I was forced, presumably by a large green, and particularly ugly troll masquerading as a programming teacher, to use multiple JOption panes for input and output then here's how I'd tackle the problem. This is meant for your information only... if you hand this in as your own work your teacher will smell a rat, and trolls have google too.
package forums;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/**
* Compares total cost of mortgages (aka ordinary annuity certains)
*/
public class MortgageCalculator
{
public static void main(String[] args)
{
// 1. input
final double price = Enter.aDouble("the purchase of the property");
final double deposit = Enter.aDouble("down payment");
Loan.setPrinciple(price - deposit);
int numLoans = Enter.anInteger("number of loans to compare");
Loan[] loans = new Loan[numLoans];
for ( int i=0; i<numLoans; ++i ) {
loans[i] = new Loan(
Enter.aDouble("Annual interest rate for Loan " + (i+1) + " (eg: 6.75)") / 100.0 / 12.0
, Enter.anInteger("number of years for Loan " + (i+1) + " (eg 20)") * 12
);
}
// 3. Output
final String caption =
"Principle " + Format.money(Loan.getPrinciple())
+ " = Price " + Format.money(price)
+ " - Deposit " + Format.money(deposit);
StringBuilder results = new StringBuilder(64 + numLoans * 64);
results.append("Monthly Rate, Months, Monthly Repayment, Total Repayments\n");
for ( Loan l : loans ) {
results.append(String.format("%5s, %d, %13s, %13s\n"
, Format.percent(l.rate)
, l.periods
, Format.money(l.payment())
, Format.money(l.totalPayment())
));
}
JOptionPane.showMessageDialog(null, results.toString(), caption, JOptionPane.INFORMATION_MESSAGE);
}
static class Format
{
static java.text.Format MONEY = new DecimalFormat("$#,###.##");
static String money(double amount) {
return MONEY.format(amount);
}
static java.text.Format PERCENT = new DecimalFormat("0.###%");
static String percent(double amount) {
return PERCENT.format(amount);
}
static StringBuilder join(String between, Object... values) {
StringBuilder result = new StringBuilder(values.length * 16);
if ( values.length > 0 ) {
result.append(values[0].toString());
for ( int i=1; i<values.length; ++i ) {
result.append(between)
.append(values[i].toString());
}
}
return result;
}
} // end class Format
static class Enter
{
public static int anInteger(String fieldDesc) {
return Integer.parseInt(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
public static double aDouble(String fieldDesc) {
return Double.parseDouble(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
} // end class Enter
} // end class MortgageCalculator
class Loan
{
private static double principle = 34324.121221312432;
final double rate;
final int periods;
static void setPrinciple(double principle) {
if (Loan.principle != 34324.121221312432)
throw new ReadOnlyException("The Principle can't be changed once set.");
Loan.principle = principle;
}
static double getPrinciple() {
return Loan.principle;
}
/**
* Initialises a new loan objects
* #param double rate The interest rate per period, as a percentage.
* eg: 0.00625 is 7.5% per annum.
* #param int periods The number of periods of the loan, typically months.
*/
Loan(double rate, int periods) {
this.rate = rate;
this.periods = periods;
}
// 2. processing
double payment() {
return principle * rate / (1 - 1/Math.pow(1+rate,periods) );
}
double totalPayment() {
return periods * payment();
}
}
class ReadOnlyException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public ReadOnlyException(String message) {
super(message);
}
}
The "list of loans to compare" is represented by an array of Loan objects... I.e: each "loan option" is represented by an instance of the Loan class, which groups all the attributes of a particular loan into one nice tidy "thing" which we can then manipulate as a whole. This a better appraoch than the technique you're using to store loan attributes, which is called "parallel arrays"... and well, umm, it's a bit outdated, in-fact it's got a (greasy) mullet, it's wearing a (too tight) orange safari suit with a (safron pink) head-band... It wasn't a good look in the eighties, and these days, well it's likely to get you beaten-up, arrested, or both; depending on your locale... Basically: We have have better ways now!
The Loan class also has a couple of handy "calculated fields" to do the computations for us. This means that if the WAY we calculate repayments changes for some reason in future, we only have one place to change it, and everything that uses Loans (which could be reading, writing, permuting, totalling, repossessing, or even wholesaling loans) does NOT have to change... they just pick up the change "for free".
In this contrived use-case all our Loans will be for the same ammount, only the interest rates and periods vary... so the Loan class also has a static variable called "principle", which holds THE "common" principle for ALL instances of the Loan class. The principle may only be set once. Any subsequent attempt to set the prinicple will cause a ReadOnlyException to be thrown.
Anyway, I hope that you learn something from seeing another way to tackle some of the sub-problems you may have dicovered while doing this exercise yourself. One tip for the future: Grab your class-mates code for this exercise and read through it... you can learn a LOT from how other people tackle things.
Cheers. Keith.
Now you need to examine the result returned by showMessageDialog(), as shown here.
String.format("\t \t \t \t \t \n", sellingPrice, ...
That's just going to output 5 tabs. You want
String.format("%s %s %s %s %s %n", sellingPrice, ...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray));
}
You haven't told us what the problem is, but I don't think this bit is doing what you want. You're asking the program to print out the entirety of your three arrays every time the loop goes round. Instead, you probably want to access the specific array element for each loan, right? Something like...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ annualInterestRatesArray[i], numberOfYearsArray[i], monthlyPaymentArray[i]);
}
Your JOptionPane.showMessageDialog(null... is inside a for loop. So it will show it as many times as the value of numberOfLoans2 . If you dont want that, move your
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
outside the for-loop.
In your answer printing method the numberOfLoans2 variable is used in two places: in a for loop making the printing happen many times (outer loop) and in a for loop making the mathematic calculation (inner loop). Probably the outer one is with no use, so remove it and the result may be shown once. Remember to remove the ending } on the end of the loop element to keep the structure ok :)

Java applying multiply to each item in an array

Alright, so I'm trying to create a "sales tax program' where the user can input the items and it adds it to an array, called "costArray". I only know how to do it, almost, with a String (since I need costArray.length for the loop) but I'm kind of lost. Can anyone help point me in the right direction so I can: Take an array of numbers (doubles) and apply a multiplier to it (0.08 for sales tax percentage) and output a total number (double)? Here is what I have so far, can you tell me if I'm close? Thanks!:
public class Input
{
private Scanner keybd;
private String item;
private double cost;
private String[] costArray;
private String[] itemArray;
/**
* Constructor for objects of class Scanner
*/
public Input(int anyAmountofItems)
{
keybd = new Scanner(System.in);
costArray = new String[anyAmountofItems];
itemArray = new String[anyAmountofItems];
}
/**
* Mutator method to set the item names and costs
*/
public void setArray(){
for(int index=0; index < itemArray.length; index++){
System.out.println("Enter the item name: ");
itemArray[index] = keybd.next();}
for(int indexa=0; indexa < itemArray.length; indexa++){
System.out.println(itemArray[indexa]);
}
for(int indexb=0; indexb < costArray.length; indexb++){
System.out.println("Enter the item cost: ");
costArray[indexb] = keybd.next();}
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println(costArray[indexc]);
}
}
/**
* Accessor method to return the items cost with tax
*/
public double getTax(){
return costArray.length;
}
// /**
// * Mutator method to calculate tax on each item
// */
// public void calculateTax(){
// for(int index=0; index < costArray.length; index++){
// System.out.println(0.08 * costArray[index]);
// }
// }
}
The number ist stored in a String and you have to "convert" it to a real number (a double value)
The way to do it is shown here:
String s = "-1.234";
double value = Double.parseDouble(s);
In Java 8:
import java.util.stream.DoubleStream;
double taxCoef = 0.08;
double[] prices = {10,20,30};
double total = DoubleStream.of(prices).map(p->p*(1+taxCoef)).sum();
System.out.println(total);
output: 64.80000000000001
(alternatively, can sum up first and then multiply)
Arrays are a bad idea, if you don't know before which size they will have. Why not use an ArrayList? If you don't know it right know: You'll really will need it often!
Names of indexes inside a loop are well with 'i', 'n', 'p, q, r' or 'x', and they only exist in their own loop, so you can define a new 'i' in the second loop - no need for indexa, indexb, ... .
For learning, a double might be sufficient, but in real world, you shouldn't use double for Money amounts, but BigDecimal. The bit-representation of fractions leads else to surprising effects.
And Scanner has already methods like scanner.nextDouble () to read a Number.

Categories

Resources