Java applying multiply to each item in an array - java

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.

Related

Take Average of an Array using Recursion

I'm trying to create a program that will take a user input, input that data into an dynamic array, and then recursively finds the average. The first part of my code works. This allows the newly created array to be passed to the method.
public static void main(String args[])
{
int i = 0;
int sum = 0;
double runningTotal = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
}
findAverage();
for (i=0; i < newClassSize.length; i++){
sum = sum + newClassSize[i];
}
System.out.println(Arrays.toString(newClassSize));
keyboard.close();
}
}
This is where I'm getting confused and confusing myself however. How would I pass the newly created array to the findAverage() method? I would then need to also have that be saved to an accumulator and then devided. Is there a better way to do this? This is my current findAverage() method but I'm confusing myself on my implementation.
public double findAverage(int classAverage, int baseCase, double runningAverage)
{
runningAverage = 0;
int sum = 0;
if (newClassSize.length - 1 > baseCase)
runningAverage = newClassSize.length;
return findAverage();
System.out.println("The class average is " + classAverage);
}
Hopefully I understood your question correctly but heres how to do it below.
The basic idea is that when the index reaches the length of the array in the
recursive function that's the base case. So all you have to do is add to the sum at each index point in the array, and just keep passing in the updated index and sum into the recursive function.
class Main {
public static void main(String[] args) {
int newClassSize[] = {1,2,3}; // User Input let say
double average = findAverage(newClassSize);
System.out.println(average);
}
public static double findAverage(int[] arr){
// Avoid division by zero error
if (arr.length==0){
return 0;
}
return findAverageHelper(arr,0,0);
}
public static double findAverageHelper(int[] arr, int index,int sum){
if (index==arr.length){ // Base Case
return (double) sum/arr.length;
}
// Increase index and add current value at index to sum
return findAverageHelper(arr,index+1,sum+=arr[index]);
}
}

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 do I create a class with arrays and then pass values to a program?

I have an assignment for my class that goes like this:
"Write a Payroll class that uses the following arrays as fields:
employeeID - An array of seven integers to hold employee identification numbers.
The array should be initialized with the following numbers:
5658845 4520125 7895122 8777541 8451277 1302850 7580489
hours - An array of seven integers to hold the number of hours worked by each employee.
payRate - An array of seven doubles to hold each employee's hourly pay rate.
wages - An array of seven doubles to hold each employee's gross wages.
The class should relate the data in each array through the subscripts.
For example, the number in element 0 of the hours array should be the number of hours worked by the employee
whose identification number is stored in element 0 of the employeeID array.
That same employee's pay rate should be stored in element 0 of the payRate array.
In addition to the appropriate accessor and mutator methods,
the class should have a method that accepts an employee's identification number
as an argument and returns the gross pay for that employee.
I'm having trouble passing values from the program I created. Here is the class:
public class moduleArray2
{
final int NUM_EMPLOYEES = 7;
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int[] hours = new int[NUM_EMPLOYEES];
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
int employee = 0;
double wage = 0;
// setHours method
public void setHours(int[] time)
{
time = hours;
}
// setPayRate method
public void setPayRate(double[] pay)
{
pay = payRate;
}
// setWages method
public void setWage(int[] time, int[] pay)
{
for (int index = 0; index < NUM_EMPLOYEES; index++)
wages[index] = time[index] * pay[index];
}
//getEmployeeID method
public int getEmployeeID(int index)
{
return employee;
}
// getWage method
public double getWage(int index)
{
return wage;
}
}
The program is supposed to display each employee number and ask the user to enter that employee's hours and pay rate. It should then display each employee's identification number and gross wages. When I run the program, it simply lists everything as a zero value, including the employee ID numbers.
import java.util.Scanner;
public class moduleArrayDemo2
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 7;
int[] time = new int[NUM_EMPLOYEES];
double[] pay = new double[NUM_EMPLOYEES];
// Create new Scanner object
Scanner keyboard = new Scanner(System.in);
// Create employee object
moduleArray2[] employee = new moduleArray2[NUM_EMPLOYEES];
// A loop that creates objects for each element
for (int i = 0; i < employee.length; i++)
employee[i] = new moduleArray2();
for (int i = 0; i < employee.length; i++)
{
System.out.print("Enter hours for Employee #" + employee[i].getEmployeeID(i) +
": ");
time[i] = keyboard.nextInt();
employee[i].setHours(time);
System.out.print("Enter how much Employee #" + employee[i].getEmployeeID(i) +
" makes per hour: ");
pay[i] = keyboard.nextDouble();
employee[i].setPayRate(pay);
}
for (int i = 0; i < employee.length; i++)
{
System.out.println("Employee #" + employee[i].getEmployeeID(i) +
" Wages: " + employee[i].getWage(i));
}
}
}
I can do arrays in a simple program, and I can do classes with programs that create instances of those classes. Arrays in a class...I feel totally lost. How do I reference the arrays in the class to get values in the program itself? Any feedback or suggestions would be greatly appreciated!
First of all you're messing up accessor methods arguments, their actual values and accessed objects.
class ModuleArray2
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int NUM_EMPLOYEES = employeeID.length; // I assume you've got it defined somewhere
int[] hours = new int[NUM_EMPLOYEES];
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
// setHours method - will reassign the whole array of `hours` with the provided argument `time` ; I'm leaving this method with a signature that you have provided just to have a place to put my comment on it
public void setHours(int[] time) {
hours = time;
// time = hours; // this is wrong - it would assign class field value to the temporary argument variable `time`, and then just throw it away (since `time` in this scope is temporary)
}
// setHours method - will set working hours in one of an array `hours` elements specified by the provided index - number of an employee it refers to
public void setHours(int employeeNumber, int workedHours) {
hours[employeeNumber] = workedHours;
}
// setPayRate method - same as above
public void setPayRate(int employeeNumber, double payRate) {
payRates[employeeNumber] = payRate;
}
// setWage method - same as above
public void setWage(int employeeNumber, double wage) {
wages[employeeNumber] = wage;
}
// getWage method - will return the wage for employee given by an index in array number
public double getWage(int employeeNumber) {
return wages[employeeNumber];
}
//getEmployeeID method - will return an ID of employee given by an index in array number
public int getEmployeeID(int employeeNumber) {
return employeeID[employeeNumber];
}
//getEmployeeIndexFromID method - will return the index of employee given by his ID number - this is inverse function of the function 'getEmployeeID'
public int getEmployeeIndexFromID(int employeeID) {
int index;
// search implementation goes here
// you should try to write it on your own
return index;
}
}
based on the Tax program change the total variable to an array that accepts 5 double values from the user then pass it to the tax method to get the tax on the total.

Setting array to null in the right place in code Java

I have my code working right, the only problem is that my output isn't correct because I can't find the right place to set the array of numbers back to zero. The basis of the programs is to take in data that contains names with corresponding grades. My output should follow this criteria:
Alice [87, 99, 96, 99, 86, 96, 77, 95, 70, 88]
Name: Alice
Length: 10
Average: 89.30
Median: 91.5
Maximum: 99
Mininum: 70
I get the first person's results correct, however, the ones that follow are incorrect because they contain all of the values being read in for every person. So, the next person will have "Alice's" grades plus their own when my code performs operations on the array for that person. I have two programs, the first is the main program that reads the data in and calls the methods to print and operate. The second is the class with all the methods that perform the operations.
This is the main program:
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
sgrades = null;
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
grades = null;
}
}
I've tried adding place to erase the values of the array for the next person by setting it to null. I've had no luck with this.
This is the next program, which contains the methods.
public class Grades {
private String studentName; // name of course this GradeBook represents
private int[] grades; // array of student grades
/**
* #param studentName The name of the student.
* #param grades The grades for the student.
*/
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
} // end two-argument GradeBook constructor
/**
* Method to convert array to a string and print.
*
* #return The name of the student with array of grades.
*/
public String toString() {
return (String) studentName + " " + Arrays.toString(grades);
}
/**
* One-argument constructor initializes studentName.
* The grades array is null.
*
* #param name The name of the student.
*/
public Grades(String name) {
studentName = name; // initialize courseName
} // end one-argument Grades constructor
/**
* Method to set the student name.
*
* #return The name of the student.
*/
public String getName() {
return studentName;
} // end method getCourseName
/**
* Method to set the length of the amount of grades.
*
* #return Number of grades for student.
*/
public int length() {
return grades.length;
}
/**
* Determine average grade for grades.
*
* #return the average of the grades.
*/
public double average() {
double total = 0; // initialize total
double average = 0.0;
// sum grades for one student, while loop
int index = 0;
while (index < grades.length) {
int grade = grades[index]; // get grade at index
total += grade;
index++; // need to increment
}
average = total / grades.length;
// return average of grades
return (double) average;
} // end method getAverage
/**
* Determine median grade for grades.
*
* #return the median of the grades.
*/
public double median() {
Arrays.sort(grades); //sort grades array
double median = 0.0;
if (grades.length%2 == 0) //checks to see if amount of grades is even/odd
//this is median if list of grades is even
median = ((double)grades[grades.length/2-1] + (double)grades[grades.length/2])/2;
else
//this is median if list of grades is odd
median = (double) grades[grades.length/2];
return (double) median;
}
/**
* Find minimum grade.
*
* #return the minimum grade.
*/
public int minimum() {
int lowGrade = grades[0]; // assume grades[0] is smallest
// loop through grades array, for loop
for (int index = 0; index < grades.length; index++) {
int grade = grades[index]; // get grade at index
// if grade lower than lowGrade, assign it to lowGrade
if (grade < lowGrade)
lowGrade = grade; // new lowest grade
} // end for
return lowGrade; // return lowest grade
} // end method getMinimum
/**
* Find maximum grade.
*
* #return the maximum grade.
*/
public int maximum() {
int highGrade = grades[0]; // assume grades[0] is largest
// loop through grades array, for-each loop
for (int grade : grades) {
// if grade greater than highGrade, assign it to highGrade
if (grade > highGrade)
highGrade = grade; // new highest grade
} // end for
return highGrade; // return highest grade
} // end method getMaximum
}
My main question is, how can I "refresh" the array for every new student that I read in?
You're looking for gradeList.clear(). But why are you copying everything from gradeList to sgrades? Seems kind of redundant.

Adding a list of user-inputted doubles to an Array

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);
}

Categories

Resources