I'm trying to add entries to an ArrayList in Java and I had it working, but now it isn't. Here is the code
import java.util.*;
public class SalesPerson
{
// define an array of allowable sales person to be three
static String[] salesPerson = new String[3];
/**
* Calculates the total annual compensation for a salesperson by
* multiplying annual sales by commission rate and then adding the salary
*/
public static void compensation()
{
try {
String[] salesperson = new String[3];
// use scanner class to read input from the user
Scanner input = new Scanner(System.in);
// List to add entries to an array list
ArrayList<String> list = new ArrayList<>();
// do..while loop to add salespersons
do {
System.out.println("Want to compare additional " //GLD-changed verbiage here
+ "salespeople? (y/n)"); //GLD-changed verbiage here
if (input.next().startsWith("y")) {
System.out.println("Enter the salesperson's name:");
addSalesPerson(list).add(input.next());
System.out.println("Enter annual amount for salesperson");
addSalesPerson(list).add(input.next());
} else {
break;
}
}
while (true);
// System.out.println(addSalesPerson(list).get(1));
// check to see if only two sales persons have been entered
if (addSalesPerson(list).size() < 2 || addSalesPerson(list).size() > 4) {
throw new Exception("You may only enter two sales persons.");
}
Object[] arr;
arr = addSalesPerson(list).toArray(new String[addSalesPerson(list).size()]);
// loop through the length of the array
for (Object arr1 : arr) {
salesperson = (String[]) arr;
}
// for this, we will compare two sales people only
float sale2 = Float.parseFloat(salesperson[1]);
float sale4 = Float.parseFloat(salesperson[3]);
// subtract based on which variable is greater to ensure no negative values
float difference = sale2 > sale4 ? sale2 - sale4 : sale4 - sale2;
// print out the difference
System.out.printf("To match the other sales person's amount "
+ "you will need to get $%.2f more\n\n", difference);
} catch (Exception e) {
// handle any exception by displaying an error message
System.out.println("Something went wrong while processing your "
+ "input. Please be sure you only entered numeric values"
+ " and or the correct amount of salespersons.");
}
}
/**
* Adds sales people to an array list
* #param salesperson
* #return ArrayList
*/
static public ArrayList addSalesPerson(ArrayList<String> salesperson)
{
for (int i=0; i<salesPerson.length; i++) {
if (salesperson.get(i).equals("")) {
break;
}
salesperson.add(salesperson.get(i));
}
return salesperson;
}
}
And then I am calling these static methods in two other files
public class Getters
{
public static void handleSalesPersonCompensation()
{
SalesPerson.compensation();
}
}
public class ComparisonWk5
{
public static void main(String args[])
{
Getters.handleSalesPersonCompensation();
}
}
The output of these should be
Want to compare additional salespeople? (y/n)
y
Enter the saleperson's name: My Name
Enter the annual amount for salesperson: 200000
Want to compare an additional salespeople? (y/n)
y
Enter the saleperson's name: My Name 2
Enter the annual amount for salesperson: 100000
To match the other person's amount, you will need to get $100000 more
But the output is:
Want to compare additional salespeople? (y/n)
y
Enter the salesperson's name:
Something went wrong while processing your input. Please be sure you only entered numeric values and or the correct amount of salespersons.
Everytime after I type "y", it shows the salesperson's name input but also displays the exception right after without having the ability to enter a name.
Any help would be appreciated
The stack trace is this:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at SalesPerson.addSalesPerson(SalesPerson.java:96)
at SalesPerson.compensation(SalesPerson.java:48)
at Getters.handleSalesPersonCompensation(Getters.java:61)
at ComparisonWk5.main(ComparisonWk5.java:31)
Thanks
Related
I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.
I'm stumped on how to format my menu. What I have so far isn't working but I know it could be better formatted and shorter. This is the description of the assignment. You can see that my approach isn't going to work but I don't know how to change my approach...
I'm pretty sure I need to use arrays but I'm not sure how to store a public array so any method can call and store information to it.
import java.util.Scanner;
/*
#author David Jacobsen
#version 10-23-16
*/
/*
CODE DESIGN:
-> Bring menu from basicMenu assingment [X]
-> Adapt for this assignment [X]
-> Add content for new menu style []
-> Adapt loop position from basicMenu []
-> Add interior loops []
-> Capitalize class name for *proper grammer* [X]
For Display Cart have three seperate totals for each item then divide by each total by its respective items total
to find the number of that item the customer has purchased and assign it to a varible to be added into menu print out.
For Print Recipt have the system call 'display cart' and add a subtotal, tax, and total printer to the end.
Loop with basic menu while looper. (method 'startOver').
*/
public class CheckoutCounter {
public static void main(String[] args) {
while (startOver() == true) {
//Define Menu Bins
//Top Menu Choice Printer
System.out.println("1. Purchase Items");
System.out.println("2. Display Cart");
System.out.println("3. Print Your Recipt");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Purchase Items"
if (doubleA <= 1) {
priceTotalDragonfruit = priceTotalDragonfruit + CheckoutCounter.purchaseItems();
}
//Menu Choice "Print Recipt"
else if (doubleA >= 3) {
CheckoutCounter.printRecipt();
}
//Menu Choice "Display Cart"
else {
CheckoutCounter.displayCart();
}
}
}
//Purchase Items Method
public static double purchaseItems() {
//Define Variables and Initialize
double dragonfruit = 5.99;
double organicBlasphemy = 99.99;
double dayOldAnswerToTheUniverse = 100000;
double total = 0;
double multiplier;
//Define Total Containers and Initialize
double priceTotalDragonfruit = 0;
double priceTotalOrganicBlasphemy = 0;
double priceTotaldayOldAnswerToTheUniverse = 0;
//Top Menu Choice Printer
System.out.println("1. Dragonfruit ($5.99/lb)");
System.out.println("2. Organic Blasphemy ($99.99 per comment)");
System.out.println("3. 1 Day Old Answer to the Universe ($100,000 per request)");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Dragonfruit"
if (doubleA <= 1) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalDragonfruit = total + (5.99 * multiplier);
}
//Menu Choice "1 Day Old Answer to the Universe"
else if (doubleA >= 3) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotaldayOldAnswerToTheUniverse = total + (100000 * multiplier);
}
//Menu Choice "Organic Blasphemy"
else {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalOrganicBlasphemy = total + (99.99 * multiplier);
}
}
//Display Cart Method
public static void displayCart() {
}
//Print Recipt/End Program Method
public static void printRecipt() {
}
//Start Over Loop Method
public static boolean startOver() {
Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter either 'True', to continue, or 'False', to stop: ");
Boolean userInputA;
userInputA = inputScanner.nextBoolean();
boolean goAhead;
if (userInputA == false) {
goAhead = false;
}
else {
goAhead = true;
}
return goAhead;
}
}
This is actually a good exercise for a student like you. I wont give you the exact answer (there are many ways though) but let me help you analyze this.
Java is an OOP language. The first thing to do is always determine what your domain objects would be.
Based on your requirement, it is asking for a Menu and create a method for each of the things it does. (sounds like an Object, yes?)
It should look something like below:
public class Menu{
public void purchaseItems(){ // pass an argument or return something depending on what you need
// figure out how you purchase items
}
public void displayCurrentPurchases(){
// figure out how you display the cart (your cart can be a List, Map, or even a class)
}
public void printReceipt(){
// figure out how you print the receipt
//somewhere here you would need to call your computeTaxes method
double netAmount = computeTaxes(grossAmount);
}
/* It's a good idea to limit a method to doing only one thing as much as possible, so you might need to make private methods such as computing for taxes below */
private double computeTaxes(double totalAmount){
return total * 0.098;
}
// and so on...
}
Now that you've got your Menu object set, you can create your Main class to actually create an instance of your Menu:
public class MainClass{
public static void main(String[] args) {
Menu menu = new Menu();
/* create your scanner here, and call the methods on the Menu depending on the user's choice */
// a switch for the user's selection might be a good idea:
switch(selected){
case 1:
menu.purchaseItems();
break;
case 2:
// you get the point. I leave this to you.
default:
sysout("Invalid selection");
break;
}
}
}
I'm having problems finding out how to get the output based on the user inputs for my Main class. I already have keyboard entry where the users can enter a value, which will be held. I'm guessing I will need to use that e.g. (input.input1());. However I also need to include the method which calculates the result e.g calculations.theAverageMassFfTheVehicle from the CalculatingRocketFlightProfile class, I'm just not sure how to combine the two to get the result.
//Calculations class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Constructor for this class
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Returns - GET
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
//Main class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.input1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.input2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.input3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.input4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.input5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.input6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry
public class kbentry{
double input1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTotalImpulse = Integer.parseInt(strTotalImpulse);
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString());
}
The problem is that you're CalcultingRocketFlightProfile class needs parameters, but you're creating calculations without passing any parameters to the new CalcultingRocketFlightProfile.
You should store those inputs in variables, then pass those variables to the constructor in your new CalcultingRocketFlightProfile that you declare.
Well, first off you are not actually passing any of your input to the Calculations class. I am not sure what input.input1() is or if you have an input class that you did not post. Either way you can do this a couple different ways.
First off give your input variables a meaningful name so you know which ones you are dealing with. Then pass all of your input.
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(input1, input2, etc..)
or
Place all your input variables into your calculations class. Then store user input as calculations.totalImpulse, etc... Then you call your calculation methods to display answers.
-EDIT-
Just have 2 classes, your main and calculations class. There is no need for another class just to handle keyboard input.
Example
Main class
public class Main {
public static void main( String args[] ) {
Scanner keyboard = new Scanner(System.in);
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.print("\nPlease enter a number for Total Impulse: " );
calculations.totalImpulse = keyboard.nextDouble();
System.out.println("You have entered : " + calculations.totalImpulse);
}
}
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
// Do all of your maths, and methods for answer return
}
You were not actually taking the keyboard input and assigning it to anything. Using a scanner object you can assign the input to a variable in your calculations class. If you do that for all of them, you dont actually need a constructor in your calculations class, you just use it to do all that math and return answers.
My code is not working and I have no idea why. This is the error I'm receiving:
Exception in thread "main" java.util.NoSuchElementException
at java.util.AbstractList$Itr.next(AbstractList.java:350)
at java.util.Collections.max(Collections.java:638)
at Project01.getHighestDollarAmount(Project01.java:120)
at Project01.main(Project01.java:45)
I need to take 2 arrayLists (Quantity, Prices) and multiply the values of the 2 and store them in a new arrayList and then find the min and max of that arrayList.
My code:
import java.util.*;
import java.io.*;
public class Project01 {
public static void main(String[] args) {
ArrayList<String> Titles = new ArrayList<String>();//Declare the array lists that will be used.
ArrayList<String> Types = new ArrayList<String>();
ArrayList<Double> Prices = new ArrayList<Double>();
ArrayList<Integer> Quantities = new ArrayList<Integer>();
ArrayList<Double> Dollars = new ArrayList<Double>();
int count = 0;//Set the counter to zero.
Scanner in = new Scanner(System.in);//Establish the scanner so user input can be properly read.
String database = getFile(in);//Setting the file name variable from the method below that asks the user for the file's name.
try {
File file = new File(database);
Scanner inputFile = new Scanner(file);
System.out.println();
System.out.println("Product Summary Report");
System.out.println("------------------------------------------------------------");
while (inputFile.hasNextLine()) {
getTitle(Titles, inputFile.nextLine());
getQuantity(Quantities, inputFile.nextInt());
inputFile.nextLine();
getPrice(Prices, inputFile.nextDouble());
inputFile.nextLine();
getType(Types, inputFile.nextLine());
System.out.println("Title: " + Titles.get(count));
System.out.println(" Product Type: " + Types.get(count));
System.out.println(" Price: " + Prices.get(count));
System.out.println(" Quantity: " + Quantities.get(count));
System.out.println();
count++;
}
System.out.println("-----------------------------------------------------------------");
System.out.println("Total products in database: " + count);
Integer index = getLargestQuantityTitle(Quantities);
System.out.println("Largest quantity item : " + Titles.get(index) + " (" + Types.get(index) + ")");
Double highestTotalDollarAmount = getHighestDollarAmount(Dollars);
System.out.println("Highest total dollar item: $" + highestTotalDollarAmount);
Integer index2 = getSmallestQuantityTitle(Quantities);
System.out.println("Smallest quantity item: " + Titles.get(index2) + " (" + Types.get(index2) + ")");
System.out.println("Lowest total dollar item: ");
System.out.println("-----------------------------------------------------------------");
inputFile.close();
} catch (IOException e) {
System.out.println("There was a problem reading from " + database);
}
in.close();
}
private static String getFile(Scanner inScanner) {
System.out.print("Enter database filename: ");
String fileName = inScanner.nextLine();
return fileName;
}
private static void getTitle(ArrayList<String> Titles, String title) { //This method is creating the array list of the titles from the input file.
Titles.add(title);
}
private static void getType(ArrayList<String> Types, String type) { //This method is creating the array list of the types from the input file.
Types.add(type);
}
private static void getPrice(ArrayList<Double> Prices, double price) { //This method is creating the array list of the prices from the input file.
Prices.add(price);
}
private static void getQuantity(ArrayList<Integer> Quantities, int quantity) { //This method is creating the array list of the quantities from the input file.
Quantities.add(quantity);
}
private static Integer getLargestQuantityItem(ArrayList<Integer> Quantities){ //This method is determining the maximum value within the quantities array list.
return Collections.max(Quantities);
}
private static Double getHighestPricedItem(ArrayList<Double> prices){ //This method is determining the maximum price within the prices array list.
return Collections.max(prices);
}
private static Integer getHighestTotalDollarItem(ArrayList<Integer> Prices){ //This method is determining the maximum total value, basically the highest quantity of the item multiplied by it's price.
return Collections.max(Prices);
}
private static Integer getSmallestQuantityItem(ArrayList<Integer> Quantities){ //This method is determining the minimum value within the quantities array list.
return Collections.min(Quantities);
}
private static Integer getLargestQuantityTitle(ArrayList<Integer> Quantities){
int index = 0;
Integer largestQuantityMainVariable = getLargestQuantityItem(Quantities);
for (int i = 0; i < Quantities.size(); i++) {
if (Quantities.get(i) != null && Quantities.get(i).equals(largestQuantityMainVariable)) {
index = i;
break;
}
}
return index;
}
private static Integer getSmallestQuantityTitle(ArrayList<Integer> Quantities){
int index2 = 0;
Integer smallestQuantityMainVariable = getSmallestQuantityItem(Quantities);
for (int i = 0; i < Quantities.size(); i++) {
if (Quantities.get(i) != null && Quantities.get(i).equals(smallestQuantityMainVariable)) {
index2 = i;
break;
}
}
return index2;
}
private static ArrayList<Double> Dollars (ArrayList<Integer> Quantities, ArrayList<Double> Prices){
int counter=0;
while (counter<Quantities.size()){
ArrayList<Double> Dollars = new ArrayList<Double>();
Dollars.add(Quantities.get(counter)*Prices.get(counter));
counter++;
}
return Dollars(null, null);
}
private static Double getHighestDollarAmount(ArrayList<Double> Dollars){ //This method is determining the maximum price within the prices array list.
return Collections.max(Dollars);
}
}
My output:
Enter database filename: /Desktop/proj1_input
Product Summary Report
------------------------------------------------------------
Title: The Shawshank Redemption
Product Type: DVD
Price: 19.95
Quantity: 100
Title: The Dark Knight
Product Type: DVD
Price: 19.95
Quantity: 50
Title: Casablanca
Product Type: DVD
Price: 9.95
Quantity: 137
Title: The Girl With The Dragon Tattoo
Product Type: Book
Price: 14.95
Quantity: 150
Title: Vertigo
Product Type: DVD
Price: 9.95
Quantity: 55
Title: A Game of Thrones
Product Type: Book
Price: 8.95
Quantity: 100
-----------------------------------------------------------------
Total products in database: 6
Largest quantity item : The Girl With The Dragon Tattoo (Book)
Exception in thread "main" java.util.NoSuchElementException
at java.util.AbstractList$Itr.next(AbstractList.java:350)
at java.util.Collections.max(Collections.java:638)
at Project01.getHighestDollarAmount(Project01.java:120)
at Project01.main(Project01.java:45)
Input File (.txt file):
The Shawshank Redemption
100
19.95
DVD
The Dark Knight
50
19.95
DVD
Casablanca
137
9.95
DVD
The Girl With The Dragon Tattoo
150
14.95
Book
Vertigo
55
9.95
DVD
A Game of Thrones
100
8.95
Book
I see where you have a problem. You are initializing ArrayList in Dollars method on each iteration of while.
Change this code
while (counter<Quantities.size()){
ArrayList<Double> Dollars = new ArrayList<Double>();
Dollars.add(Quantities.get(counter)*Prices.get(counter));
counter++;
}
To this
ArrayList<Double> Dollars = new ArrayList<Double>();
while (counter<Quantities.size()){
Dollars.add(Quantities.get(counter)*Prices.get(counter));
counter++;
}
so the final method should look like
private static ArrayList<Double> toDollars(ArrayList<Integer> quantities, ArrayList<Double> prices){
int counter=0;
ArrayList<Double> outputInDollars= new ArrayList<Double>();
while (counter<quantities.size()){
outputInDollars.add(quantities.get(counter)*prices.get(counter));
counter++;
}
return outputInDollars;
}
I also recomend you to use for loop, but it is up to you. Try to name variables using camelcase
I don't see the Dollars method (the one that actually multiplies the Quantities and Prices) being called at all in main. Also, you are instantiating the Dollars Arraylist within the while loop, so you will lose reference to the old data that you added in the list. If that is what you want to do, why even have a counter then?
Having a method named Dollars as well as an attribute with the same name causes a lot of confusion. Please refrain from doing so.
Use List instead of ArrayList for references. Use ArrayList only when you are instantiating the object.
Instance attribute names should start with lowercase alphabet or underscore.
Collections.max() throws a NoSuchElementException if the collection is empty. And thats ur problem. You dont add any values to the dollars list.
Plus you never call Dollars()
also update your Dollars function:
private static ArrayList<Double> Dollars (ArrayList<Integer> Quantities, ArrayList<Double> Prices){
int counter=0;
// create arrayList outside of the while and return it
ArrayList<Double> Dollars = new ArrayList<Double>();
while (counter<Quantities.size()){
Dollars.add(Quantities.get(counter)*Prices.get(counter));
counter++;
}
// you returned a call to the same function there -> recusive until death
return Dollars;
}
The method causes the exception:
private static Double getHighestDollarAmount(ArrayList<Double> Dollars) {
return Collections.max(Dollars);
}
because the ArrayList Dollars is empty.
You call that method here:
Double highestTotalDollarAmount = getHighestDollarAmount(Dollars);
The provided list Dollars is empty, because it is not used in this while loop:
while (inputFile.hasNextLine()) {
getTitle(Titles, inputFile.nextLine());
getQuantity(Quantities, inputFile.nextInt());
inputFile.nextLine();
getPrice(Prices, inputFile.nextDouble());
inputFile.nextLine();
getType(Types, inputFile.nextLine());
System.out.println("Title: " + Titles.get(count));
System.out.println(" Product Type: " + Types.get(count));
System.out.println(" Price: " + Prices.get(count));
System.out.println(" Quantity: " + Quantities.get(count));
System.out.println();
count++;
}
So, either you mixed the lists Dollars and Prices and wanted to call:
Double highestTotalDollarAmount = getHighestDollarAmount(Prices);
Or you forgot to "fill" the Dollars list somewhere.
Edit:
I've updated your Dollars method:
private static List<Double> getTotalPrices(List<Integer> quantities, List<Double> prices){
List<Double> totalPrices = new ArrayList<>();
for (int i = 0; i < quantities.size(); i++) {
totalPrices.add(quantities.get(i) * prices.get(i));
}
return totalPrices;
}
I did following changes:
I've renamed the method to getTotalPrices, because this name is more descriptive than Dollars and it follows the Java Naming Conventions (method names should start with a lowercase letter)
I've changed the types from ArrayList to List, because you should always program to an interface instead of a specific type
I've changed the names of the parameters, due to the Naming Conventions
I've replaced the while loop with a for loop, because these are better in cases like this (iterating over a list)
I've changed the returned value to the new list, instead of a recursive call (which would cause more trouble)
I'm trying to create a program that allows the user to say, input (orange/apple/banana/etc), then the quantity they want to purchase, and the program will calculate the total. However, after trying Strings (Can't multiply them) and a few other options, I'm stuck. I've intensively browsed this forum along with countless guides, to no avail.
The IF statement I inserted was simply a last ditch random attempt to make it work, of course, it crashed and burned. This is all basic stuff I'm sure, but I'm quite new to this.
I would also like to display a list to choose from, perhaps something like
Oranges: Qnty: (Box here)
Apples: Qnty: (Box here)
Bananas: Qnty: (Box here)
Etc
But I'd really settle for help as how to allow the user to input a word, orange, and it is assigned the value I have preset so I can multiply it by the quantity.
All help is appreciated, criticism too of course, to you know, a reasonable extent...
Here's my code.
/* Name 1, x0000
* Name 2, x0001
* Name 3, x0003
*/
import java.util.Scanner;
public class SD_CA_W3_TEST1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
double nameOfItem1, nameOfItem2, nameofItem3;
double quantityItem1, quantityItem2, quantityItem3;
final double apple = 0.30;
final double orange = 0.45;
final double strawberry = 2.30;
final double potato = 3.25;
final double turnip = 0.70;
final double carrot = 1.25;
double totalCost;
String strNameOfItem1;
System.out.println(" \t \t What would you like to buy today?");
System.out.print("Please choose from our fine selection of: oranges, strawberries, potatoes, turnips, and carrots. \n" );
System.out.print("Enter name of product ");
nameOfItem1 = in.nextDouble();
nameOfItem1 = If = nameOfItem1 (apple, orange, strawberry, potato, turnip, carrot);
System.out.print("Please enter a quantity to purchase");
quantityItem1 = in.nextDouble();
totalCost = quantityItem1 * strNameOfItem1;
System.out.print("The total cost of your purchase is: " +totalCost );
}
}
I would use a HashMap. Here's a good tutorial:
http://www.tutorialspoint.com/java/util/hashmap_get.htm
HashMap food = new HashMap();
food.put("Apple", 0.30);
food.put("Orange", 0.45);
...
then use
food.get("Apple");
to give you the price.
the grand total would be something like:
double quantity = 4.0;
double total = food.get("apple") * quantity;
Try using enums,
class Test{
public enum Fruits{
apple(0.30), orange(0.45), strawberry(2.30), potato(3.25);
private final double value;
Fruits(double value1){
value = value1;
}
public double getValue(){
return value;
}
}
public static void main(String[] args) {
int quantity = 0;
// Read your value here and assign it to quantity
System.out.println(Fruits.apple.getValue()*quantity);
}
}
Enum seems to be a good choice here. It would help you map your item names to the price easily instead of creating several double variables.
private enum Items {
APPLE(0.30), ORANGE(0.45), STRAWBERRY(2.30),
POTATO(3.25), TURNIP(0.70), CARROT(1.25);
double price;
Items(double price) {
this.price = price;
}
double getPrice() {
return price;
}
}
Use Scanner#next() to read in String and use Enum.valueOf() to validate and convert user input into one of your Items.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to buy today?");
System.out.println("Please choose from our fine selection of: " +
"Orange, Strawberry, Potato, Turnip, and Carrot.");
System.out.print("Enter name of product: ");
String nameOfItem = in.next();
Items item;
try {
// Validate Item
item = Items.valueOf(nameOfItem.toUpperCase());
} catch (Exception e) {
System.err.println("No such item exists in catalog. Exiting..");
return;
}
System.out.print("Please enter a quantity to purchase: ");
int quantity;
try {
quantity = in.nextInt();
if (!(quantity > 0)) { // Validate quantity
throw new Exception();
}
} catch (Exception e) {
System.err.println("Invalid quantity specified. Exiting..");
return;
}
double totalCost = quantity * item.getPrice();
System.out.printf("The total cost of your purchase is: %.2f", totalCost);
Output :
What would you like to buy today?
Please choose from our fine selection of: Orange, Strawberry, Potato, Turnip, and Carrot.
Enter name of product: Strawberry
Please enter a quantity to purchase:3
The total cost of your purchase is: 6.90