I am writing an inventory program for a book store that is comprised of two classes and multiple methods within these classes.
The method I'm having the most trouble with is my purchase() method which is supposed to interactively process a purchase, update the array after the purchase, and display totals for items sold and total amount of money made that day.
The method is supposed to follow these 10 steps:
Ask the user to enter the ISBN number of the book they'd like to purchase.
Search the array for the object that contains that ISBN.
If the ISBN isn't found in the array, display a message stating that we don't have that book.
If the ISBN is found but the number of copies is 0, display a message saying the book is out of stock.
If the ISBN is found and the number of copies is greater than 0, ask the user how many copies they'd like to purchase.
If the number they enter is greater than the number of copies of that book in the array, display a message stating that and ask them to enter another quantity.
When they enter a 0 for the ISBN, the Scanner is supposed to close
Once the purchase is complete I need to update the array by subtracting the number of copies of that particular book that was purchased.
Print the updated array.
Display a count of how many books were purchased, and how much money was made from the purchase.
But as my code is written, after the Program prompts me to enter an ISBN, nothing happens, it just continually lets me enter numbers with no additional output.
Here is the code I have for this method. I'm pretty sure it's probably an issue with my loop as I'm not very good with looping. Can anyone spot what I'm doing wrong?
public static Book[] purchase(Book[] books) {
int itemsSold = 0;
double totalMade = 0;
double price;
int copies;
String isbn;
Scanner input = new Scanner(System.in);
int desiredCopies = 0;
int index;
double total = 0;
System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
String desiredIsbn = input.next();
for (index = 0; index < books.length; index++) {
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() > 0) {
System.out.println("How many copies of this book would you like to purchase?");
if (!books[index].getISBN().equals(desiredIsbn))
System.out.println("We do not have that book in our inventory.");
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() == 0)
System.out.println("That book is currently out of stock.");
desiredCopies = input.nextInt();
}
if (desiredCopies > books[index].getCopies())
System.out.println("We only have " + books[index].getCopies() + "in stock. Please select another quantity: ");
desiredCopies = input.nextInt();
books[index].setCopies(books[index].getCopies() - desiredCopies);
if (input.next().equals(0))
System.out.println("Thank you for your purchase, your order total is: $" + total);
input.close();
total = books[index].getPrice() * desiredCopies;
itemsSold += desiredCopies;
totalMade += total;
System.out.print(books[index]);
System.out.println("We sold " + itemsSold + " today.");
System.out.println("We made $" + totalMade + "today.");
}
return books;
}
Any help would be greatly appreciated.
You are not matching every possible condition
Your if statements aren't covering all the possible permutations of conditions apparently.
You should use always use an if/else if/else block to make sure you cover all your conditions. Outside this there is absolutely no way for anyone to provide any actual solution with so little to go on.
Also
Scanner and StringTokenizer are two of the worst designed classes in the JDK outside Date and Calendar. They cause endless trouble for new people and are avoided by the veterans.
Related
I am working on this program with these instructions:
Bus Passengers: Write a program that is to be used to count how many passengers are travelling on
buses that pass a particular bus stop in a given hour. It should use a while loop to repeatedly ask the user to give the number of passengers on the bus that just passed. It should stop when the special code X is entered as the number of passengers. It should then give the number of buses and the total number of passengers counted in that hour. For example, one run might be as follows.
How many passengers were on the bus? 2
How many passengers were on the bus? 5
How many passengers were on the bus? 10
How many passengers were on the bus? 3
How many passengers were on the bus? 12
How many passengers were on the bus? 1
How many passengers were on the bus? 0
How many passengers were on the bus? X
There were a total of 33 passengers on 7 buses.
I am trying to fix an error:
Few points to note:-
You don't need System.exit()
In java variables are only accessible inside their scope i.e. the region they are created in.
I tried to rewrite code as following:-
import java.util.Scanner;
public class Bus {
int busCount =0;
int passengerCount =0;
Scanner scanner= new Scanner(System.in);
public static void main(String args[]){
Bus bus = new Bus();
bus.getResults();
}
private void addBusAndPassenger(String input){
try{
int a = Integer.parseInt(input);
busCount = busCount + 1;
passengerCount = passengerCount + a;
}catch(NumberFormatException e){
System.out.println("Please provide integer or X as input");
}
}
private void getResults(){
String a =null;
while (!("X".equals(a))){
System.out.print("How many passengers were on the bus? ");
a = scanner.nextLine();
if("X".equals(a))
break;
addBusAndPassenger(a);
}
System.out.println("There were a total of " + passengerCount + " passengers on " + busCount + " buses.");
}
}
A few things here. Other people pointed this out, but you need to pass parameters to your method. The method signature is there for a reason - your method calls must match the method signature you define.
Also, busInformation is supposed to return an int, but it returns nothing.
Also, this line:
Integer.parseInt(a);
does nothing - you throw away the result immediately. It won't modify the string in place or anything like that. (Well, I suppose that it'll throw an exception if they enter something other than an integer, but that doesn't seem to be what you're trying to do with this line).
At an absolute minimum, you should change the return type of your method to int and the change this line to return Integer.parseInt(a);.
(You also shouldn't be creating a new scanner every time like this - you should just re-use the same one).
I am attempting to create a program that will output the value at the beginning of the year, the amount depreciated during year, and the total amount of overall depreciation for each year given in that life span. For example, if I bought an item in 2005 and its life span was 5 years, it would calculate the depreciation for that item for those 5 years.
I wasn't very sure where to start with this project and this is what I have so far. However, at this point I am stuck and now I am unsure of what to do next.
import java.util.Scanner;
public class ConnerCozineDepreciation {
public void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int item, year, cost, life, depreciationType, depreciationDuring, totalDepreciation, begPrice;
//GEt all the needed data from the user
System.out.println("What is the item");
item=keyboard.nextInt();
System.out.println("What is the year of purchase?");
year=keyboard.nextInt();
System.out.println("How much did it cost? (No decimals)");
cost=keyboard.nextInt();
System.out.println("What is the item's estimated life span in years?");
life=keyboard.nextInt();
System.out.println("What is the method of depreciation?(1 for straight line or 2 for double decline)");
depreciationType=keyboard.nextInt();
//PRints the description and other info of the item
System.out.println("Item:"+item);
System.out.println("Year of Purchase: "+year);
System.out.println("Cost of Purchase: "+cost);
System.out.println("Estimated life: "+life);
if(depreciationType ==1) {
System.out.println("Straight line");
}else{
System.out.println("Double Decline");
}
System.out.println("Year\tValue at Beginning of Year\t\t"
+"Amount Depreciated During Year\t\tTotal Depreciated at End of Year");
//Calculations of depreciations
if(depreciationType==1) {
while(year<=(year+life)){ //running only as many lines as wanted
year+=1;
//System.out.format("%-8d" + "$%-39.2d"+ "$%39.2d" + "$%42.4d%n", year, cost, depreciationDuring, totalDepreciation);
}
}else {
}
}
}
I think you're looking for decrementing the life value
while (life > 0) {
year++; life--; // as it gets more age, it has less life
}
Otherwise written as
for ( ; life > 0; life--) {
year++;
}
Based on the other conditions, you might want to try this instead, though
life -= depreciationType;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have looked all over this website and other websites trying to figure how to do this with the knowledge that my teacher has provided me.
Basically the program is supposed to be a user input system where you can make bets on a head or tails coin flipping game.
So far, I've had no luck in what to do. Not asking someone to finish it for me, but to help me in the right direction.
Thank you in advance.
Here is my code so far:
package Homework6;
import java.util.Scanner;
import java.lang.Math;
public class CoinFlip {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int money = 10;
double flip = Math.random();
String heads = "heads";
String tails = "tails";
int bet = input.nextInt();
while(bet < 0 || bet > money){
if(true){
System.out.println("How much do you want to bet?");
input.next();
}
}
System.out.println("Guess if the coin will be heads or tails.");
String guess = input.next();
String coin;
if (flip <0.5) coin = heads;
else coin = tails;
if(guess == coin){
int correct = money + bet;
System.out.println("The flip was"+ coin);
System.out.println("You win" + bet);
System.out.println("")
}
}
}
To fix the possible infinite loop:
do{
System.out.println("How much do you want to bet?");
bet = input.nextInt();
}
while(bet > 0 && bet > money);
You can drop the if statement since it's not really needed. You will however need to declare the variable bet to have the correct scope.
if(guess.equals(coin)) // proper way of checking Strings
Use this form for checking the value of the guess vs the coin.
A few notes for you (since you're starting out and still a student):
1) Your while loop is a little bit poorly constructed. That System Out will constantly be printing to the screen until there is some input. And that if statement is essentially doing no conditional checking. It is always true.
2) You never originally prompt the user for how much they want to bet. You're only prompting them after they've input a value. So when you originally hit play, the console is just blank. But really it's waiting for some input.
3) Your if statement for changing the coin state is a little extraneous.
4) The user's amount of money is never actually updated, and the output at the end could be a little more informative.
5) What if someone wins the first one and wants to play again? They probably want to keep that bank growing! So you could encompass the entire thing inside of a do/while that runs while bank > 0.
6) You should only use the == operator when comparing primitive types. Pretty much all other times, use Object.equals(object);
I know you didn't ask someone to complete it for you, but this site works best by sharing information. Below should work for you, I've commented it extensively. Hopefully this can teach some things beyond just this homework assignment.
public static void main(String[] args)
{
// Setup some initial variables
int bank = 10;
double flip = Math.random();
// Instantiate a new Scanner object
Scanner input = new Scanner(System.in);
// Let the user bet until they run out of money in the bank
do
{
// Ask the user how much money to wager
System.out.println("How much do you want to bet?");
int bet = input.nextInt();
// The bet was invalid
while(bet < 0 || bet > bank)
{
System.out.println("Invalid bet (" + bet + "). Minimum bet = 0. Maximum bet = " + bank);
bet = input.nextInt();
}
// Ask the user for which side
System.out.println("Heads or tails?");
String guess = input.next();
// The coin is either heads or tails, so it can always start as tails. If the value goes under .5, change it to heads. If not, it remains the same, "tails".
String coin = "tails";
if (flip < 0.5)
{
coin = "heads";
}
// Tell the user the result, regardless of win or lose
System.out.println("The flip was " + coin);
// Update the user's bank and inform them of the new value
if(guess.equalsIgnoreCase(coin)) // this allows for any form of HeaDs or TaILs
{
bank += bet;
System.out.println("You win " + bet);
System.out.println("Your bank contains " + bank);
}
else
{
bank -= bet;
System.out.println("You lose " + bet);
System.out.println("Your bank contains " + bank);
}
}
while(bank > 0);
// Goodbye message
System.out.println("Thanks for playing!");
// Don't forget to close your Scanner object!
input.close();
}
Alright, since you are having so much trouble with this, I will lay it out how I achieved this.
You need a couple variables, I used these below, taken from your code.
Scanner input = new Scanner(System.in);
int money = 10;
String heads = "heads";
String tails = "tails";
int bet = 0;
String guess;
String coin;
You then need a loop. You have a while loop already, and that will do, BUT your conditional is incorrect as I see it. You are testing bet < 0 || bet > money which I read as "If you bet less than no money or bet more money that you have, enter this loop" I believe you want the opposite of that. I also added if you ran out of money.
while(bet > 0 || bet < money || money <= 0)
Now for the inside of the loop. Here, you want to do a couple things in a certain order.
Ask how much they want to bet, read it in the appropriate variable.
Ask what their guess is, read it in the appropriate variable.
Use your if statement you have to determine if the flip was heads or tails, But I got rid of the flip variable, and used Math.random() < 0.5 directly.
Check their guess vs the flip. If they were correct, do what you need to do, i.e. add bet to money and display some sort of message.
If they were wrong, do what you need to do, i.e. subtract bet from money, display some message.
Then your program will start over.
My program needs to allow the user to input an employee's name and total annual sales. When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. It should then print out the difference between the two numbers.
In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.)
When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code.
I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. (I'm using NetBeans, if that's relevant.)
Any ideas would be much appreciated!
EDIT: Here is the output and error message.
Name? captain America
Input annual sales: 80
Add another employee? yes or no
no
Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58)
package commission;
//Commicaion calulator
import java.util.Scanner;
public class Commission
{
public static void main(String args [])
{
salesPerson[] emps = new salesPerson[10]; //Employee Array
String cont = "yes";
String n="";
double s=0;
int i=0;
salesPerson high = new salesPerson();
salesPerson low = new salesPerson();
// scanner object for input
Scanner keyboard = new Scanner(System.in);
//Enter in employee name
while (cont == "yes"){
System.out.print("Name? ");
n = keyboard.nextLine();
emps[i] = new salesPerson();
emps[i].setName(n);
//Loop of yes or no entering more employees
//If yes add another name if no continue with total Commision
//Enter in the sales amount of commistion
System.out.print("Input annual sales: ");
s=keyboard.nextDouble();
emps[i].pay.annual = s;
System.out.println("Add another employee? yes or no ");
keyboard.nextLine();
cont = keyboard.next(); //Line 46: Debugger stops here.
if (cont =="yes")
i++;
if (i==9){
System.out.println("You have reached the maximum number of employees.");
cont = "no";
}
}
i=0;
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
high = emps[i];
if (emps[i].pay.annual < low.pay.annual)
low = emps[i];
}
double diff = high.pay.annual - low.pay.annual;
System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());
// Output table for composation with increments of $5000
// int tempAnnual =(int) pay.annual;
// for (i=tempAnnual; i<= pay.annual; i+=5000)
// System.out.println(i+" "+ pay.getReward(i));
}
public static class totalPay
{
double salary=50000.0; //Yearly earned 50000 yr fixed income
double bonusRate1=.05; //bounus commission rate of 5% per sale
double commission; //Commission earned after a sale
double annual; //Sales inputted
double reward; // Yearly pay with bonus
double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%
public double getReward(double annual)
{
double rate;
if (annual < 80000)
rate=0;
else if ((annual >= 80000) || (annual < 100000 ))
rate=bonusRate1;
else
rate=bonusRate2;
commission = annual * rate;
reward=salary + commission;
return reward;
}
}
public static class salesPerson
{
String name; //Employee Name
totalPay pay = new totalPay();
public void setName(String n) //Name
{
name=n;
}
public String getName()
{
return name;
}
}
}
You create this array of max size 10:
salesPerson[] emps = new salesPerson[10];
but only create and assign an object reference for each SalesPerson object entered. Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. You then attempt to iterate through the entire array (emps.length is 10 ):
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual)
which leads to the NPE when indexing the first null reference. You need to change your loop to something like:
int numEntered = i; //last increment
for (i=0; i< numEnetered; i++){
if (emps[i].pay.annual > high.pay.annual)
It stops the debugger because it waits for your input using the keyboard. If you type the input and hit enter, the debugger will continue from there on.
By the way, your should read up on naming conventions and coding best practices for java
Your debugger is stopped because it's blocked on input coming in from the Scanner. This is specified in the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That aside, you're fortunate to have entered that code block at all. You're comparing Strings incorrectly, so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. This is also the reason that your NPE occurs; you're initializing elements of your array under false pretenses (== with a String), so:
You may never initialize anything
You may only initialize the first thing (if (cont =="yes"))
I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. The other errors may become easier to see once you start using .equals, but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later.
The Prompt:
A program that accepts a candy name (for example, “chocolate-covered blueberries”), price per pound, and number of pounds sold in the average month, and displays the item’s data only if it is a best-selling item. Best-selling items are those that sell more than 2000 pounds per month.
b. A program that accepts candy data continuously until a sentinel value is entered and displays a list of high- priced, best-selling items. Best-selling items are defined in Exercise 2a. High-priced items are those that sell for $10 per pound or more.
Here is an example of a good design in operation:
High-priced, Best-selling Candy
Fudge $12.50 4500 lbs
Vanilla Creme $13.75 2200 lbs.
Fudge, 12.50, 4500 Jawbreakers, 6.50, 5500 Chocolate, 14.00, 790 Butterscotch, 9.50, 4500 Vanilla Creme, 13.75, 2200
Item that sold most pounds: Jawbreakers
but the problem I am having is that my teacher is not letting me use for loops, or arrays. And I do not want to define multiple instances of the same variable because it is finite to a certain amount.... What would be the most efficient way of doing this?
start
// Declarations
num QUIT = "Y";
final String HEADING = "High Priced, Best Selling Candy" + "\n" + "\n";
final String HSPS = candyName + " " + candyPrice + " " + candySold + " ";
final String MOSTSOLD = "Item that sold the most pounds is "
while <> QUIT;
enterCandy();
printHighPriceBestSelling();
printSoldMostPounds();
endwhile;
stop
entercandy()
String candyName = "poop";
double candyPrice = 0.0;
double candyWeight = 0.0;
int candySold = 0;
output "Please enter name of candy.";
input candyName;
output "Please enter candy price.";
input candyPrice;
output "Please enter pounds sold.";
input candySold;
printHighPriceBestSelling()
if(candySold > 2000 && candyPrice > 10)
{
output HEADING;
output HSPS;
}
else
{
output "There were/are no best selling, high priced candy!"
}
printSoldMostPounds();
//There is no basis for comparison.
There are only two ways of doing this. Create lots of different, artbitrary, and predefined variables to be filled by the loop until they are overwritten. Lets say 10. Or create an array. I am sure there is an overly complex way of doing it with nested if/switch/while loops, but why teach us/force us to use the ugly inefficient way?
output "MOSTSOLD ";
I'm assuming that, besides arrays, you're teacher isn't allowing you to use any standard Collection objects.
You could always just build your own LinkedList of entered candy orders--it's ugly, but it would work. A single "link" in the chain would look like this
public class CandyOrderLink {
private String candyName;
private Double candyPrice;
private Double orderAmount;
private CandyOrderLink nextOrderLink;
public CandyOrderLink(String candyName, Double candyPrice, Double orderAmount) {
this.candyName = candyName;
this.candyPrice = candyPrice;
this.orderAmount = orderAmount;
}
public CandyOrderLink getNextLink() {
return nextOrder;
}
public void setNextLink(CandyOrderLink nextOrderLink) {
this.nextOrderLink= nextOrderLink;
}
public String getCandyName() {
return candyName;
}
public Double getCandyPrice() {
return candyPrice;
}
public Double getOrderAmount() {
return orderAmount;
}
}
Not sure if I'm quite grasping the point of the assignment, but using a list data-structure to keep track of all orders will work. Just build a link for each entry (candyName, price, amount) and set that link as the next link of the previous one. At the end of input, iterate through the list by repeatedly calling getNextLink() on each link and printing information (if appropriate). Here is Wikipedia's article on linked lists: http://en.wikipedia.org/wiki/Linked_list
From the problem's description, I see no need to store the data entered so that it can be sorted. Both a and b state simple conditions for displaying a candy: greater than 2,000 pounds and at least $10/lb. You can print each entry immediately after it is entered.
However, your example output implies that you must pick the single best-selling candy which contradicts the description. Which is correct?