How do I properly call the other methods in the main method - java

I am having trouble calling the methods on the main method. This is what I need to have in the main method:
Print the banner message
Get the product ArrayList
Get the product order from the user and check it exists in the product
ArrayList
If the product exists
Get the product price
Compute the product tax
Compute the total sale
Output the total sale
Else
Output "Product not found."
import java.util.ArrayList;
import java.util.Scanner;
public class Unit6ProblemSet {
public static void main(String[] args) {
bannerPrinter();
ArrayList<String> products = productBuilder();
Boolean productExists = getOrder(products);
if(productExists) {
double price = getPrice();
getTax(tax);
getTotal(saleTotal);
printTotal(saleTotal);
}
else {
System.out.println("Product not found.");
}
}
public static void bannerPrinter() {
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
public static ArrayList<String> productBuilder() {
ArrayList<String> products = new ArrayList<String>();
products.add("Headphones");
products.add("Pencils");
products.add("Pens");
products.add("Computers");
products.add("Videogames");
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String userStr = "";
System.out.println("Enter a product: ");
userStr = scnr.nextLine();
boolean productName = products.contains(userStr);
if (productName) {
System.out.println("True");
}
else {
System.out.println("False");
}
return productName;
}
public static double getPrice() {
double price = 0.0;
price = (Math.random() + 1) * 100;
return price;
}
public static double getTax(double price) {
double tax = 0.0;
tax = price * 0.10;
return tax;
}
public static double getTotal(double price, double tax) {
double saleTotal = 0.0;
saleTotal = price + tax;
return saleTotal;
}
public static void printTotal(double saleTotal) {
System.out.println("Your sale total is: " + saleTotal);
}
}
I am just having trouble calling the different methods in main.

You are on the right path.
bannerPrinter();
ArrayList<String> products = productBuilder();
The first line in your main method, bannerPrinter() calls your bannerPrinter method.
Now for your second call for productBuilder() you are basically getting a result back. Now using that result you can see if that product exists, get the product prices etc.
So in sort if you want to call a method from main all you have to do is use the method name to make that call.
For methods that have arguments like getOrder(ArrayList<String> products) you have to pass an argument to the method.
In your example it would be getOrder(products). that would call the method with the right argument and get a boolean result.
Also based on your recent edit when you call a method that has a return type, for example getOrder() you need to have a variable that get the result.
productBuilder() return a List<String> so you did this
ArrayList<String> products = productBuilder(); Which basically says, get my products and store them in my array list of products so I can use it.
Your other getters are doing something similar. You need to store the result and then use that to call your other methods.
I suggest you do some reading on Java in general, since this is a basic question. If this is a Java 101 type of class assignment re-read the first code chapters to get a better understanding of how methods and classes call each other.

There could be a possible issue in your getOrder method
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String userStr = "";
System.out.println("Enter a product: ");
userStr = scnr.nextLine();
//Move this after scanning user input
boolean productName = products.contains(userStr);
if (productName) {
System.out.println("True");
}
else {
System.out.println("False");
}
return productName;
}
In your main method, you keep calling the methods you need by passing the arguments they need and save their return result in a variable
public static void main(String[] args) {
bannerPrinter();
ArrayList<String> products = productBuilder();
Boolean productExists= getOrder(products); //getOrder needs arraylist and return boolean
//then check if the returned result is true i.e if product exists
if(productExists){
double price = getPrice();
//do other stuff, calcualte tax on price and then get total and etx
}
else{
//Print "product not found"
}
}

Related

Why won't my code enter into while loop after I enter a string?

I had to do a bunch of methods in my code and then have it all go to the main method. Everything is working correctly, but when I enter in a string to the "getOrder" method it won't check to see if the string is true and then finish the rest of the code. Can someone please help me? I tried doing an if and else statement, but they didn't work either. thank you
import java.util.Random;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
//Get banner message
welcomeUser();
//Get product array
String[] products = getProducts();
//Get prouct order from user aka the LA
getOrder(products);
//Does the product exist?
if(getOrder(products) == true) //yup it exists
{
//Get the *price*
getPrice();
double fPrice = getPrice();
//Get the TAX
getTax(fPrice);
double tax = getTax(fPrice);
//Get the total sale
getTotal(fPrice, tax);
//output the total sale
double transaction = getTotal(fPrice, tax);
printTotal(transaction);
}
else
System.out.print("Not found");
}
public static void welcomeUser()
{
System.out.println("Hello! Welcome to the Fruit Market!");
}
public static String[] getProducts()
{
String [] productList = new String [5];
productList[0] = "Banana";
productList[1] = "Pineapple";
productList[2] = "Grapes";
productList[3] = "Strawberries";
productList[4] = "Kiwi";
//System.out.println(Arrays.toString(productList));
return productList;
}
public static boolean getOrder(String[] stuff)
{
Scanner scan = new Scanner(System.in);
String usersFruitChoice;
System.out.println("Please enter a fruit you would like to buy.");
usersFruitChoice = scan.nextLine();
boolean valid = false;
while(!valid)
{
for (String stuff1 : stuff) {
valid = stuff1.equalsIgnoreCase(usersFruitChoice);
}
}
return valid;
}
}
}
The culprit seems to be your for loop:
for (String stuff1 : stuff) {
valid = stuff1.equalsIgnoreCase(usersFruitChoice);
}
This section of your code will iterate through your entire products array and will overwrite the value of valid if a later value in the array does not match whatever is in usersFruitChoice. Try entering Kiwi for usersFruitChoice and see if the code enters the while loop to verify that this error is occurring.
You can fix this by using a break statement if you found a valid entry that matches usersFruitChoice, as that will exit the loop early and not always cause the last value in the array to be checked against usersFruitChoice:
for (String stuff1 : stuff) {
if (stuff1.equalsIgnoreCase(usersFruitChoice)) {
valid = true;
break;
};
}
Consider removing this line - it does nothing:
//Get prouct order from user aka the LA
getOrder(products);

Trouble implementing Shoe Inventory program in Java

I am trying to implement an Inventory program for shoes. What I am trying to do is give each shoe an id (productId) and a quantity of shoes that are in stock (ammountToPick). I want to be able to ask the user running the program to enter a shoe id to get the amount of that type of shoe that are left in stock (ammountToPick). My current problem with my program is that it is not returning anything and just keeps printing "invalid product id".
I have provided my code below:
public class Product {
private String productId = "";
private int ammountToPick = 0;
private int ammountToRestock = 0;
public Product (String productId, int ammountToPick){
this.productId = productId;
this.ammountToPick = ammountToPick;
}
public String getProductId() {
return productId;
}
public int getAmmountToPick() {
return ammountToPick;
}
}
public class Shoes extends Product{
public Shoes(String productId, int ammountToPick){
super(productId, ammountToPick);
}
}
import java.util.Scanner;
public class Inventory
{
private static String productId = "";
private int ammountToPick = 0;
private int ammountToRestock = 0;
public static final int MAX_ITEMS = 999999;
private static Product product [] = new Shoes[MAX_ITEMS];
public static void main (String args[]){
buildInventory();
getInventory();
}
public static void buildInventory(){
product[1] = new Shoes("shoe101", 19);
product[2] = new Shoes("shoe200", 1);
product[3] = new Shoes("shoe420", 9);
}
public static void getInventory() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the product id of the product you would like to pick: ");
String userinput = input.nextLine();
if(userinput.equals(productId)) {
System.out.println("there are" + product[1].getAmmountToPick() +"left");
}
else {
System.out.println("invalid product id ");
}
}
}
if(userinput.equals(productId)) {
System.out.println("there are" + product[1].getAmmountToPick() +"left");
}
else {
On the first line, you problem is that productId is set to an empty string at the top of the class. It should actually work if you just hit enter without entering an actual productId and userinput is "". But to make this work the way you want, get rid of your productId variable and check if userinput matches a productId of one of the items in your array
you need to do
userinput = ...; //this part is fine
for (Product p : products) {
if (userinput.equals(p.getProductId())) {
System.out.println('there are ' + p.getAmmountToPick() + " left");
}
}
Both the Product and Inventory classes have productId member variables. You're comparing userInput to the private static productIdin the Inventory class, which is an empty string.
I think you should be iterating through your inventory array looking for a match to the productId of a Product.
Here's one way to do it with an enhanced loop and no new methods:
boolean found = false;
for (final Product aProduct: product) {
if(userInput.equals(aProduct.getProductId())) {
System.out.println("there are" + aProduct.getAmmountToPick() +"left");
found = true;
break;
}
}
if(!found) {
System.out.println("invalid product id ");
}
I'd rename the product member variable to products so its intent is clearer. It would make the code above clearer as well.
Inventory, in the way you're using it, needs no productId. It should be deleted.

Main class java does not return the value i passed in using scanner [closed]

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 7 years ago.
Improve this question
I have this main class
public class Hotel
{
Scanner scan = new Scanner(System.in);
Register[] items = new Register[15];
int count = 0;
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register deluxe = new Deluxe();
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
run.enterItems();
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
}
public double calcTotal()
{
double total = 0;
for(int i = 0;i<count;i++)
{
total += items[i].total();
}
return total;
}
that is supposed to return the value i put in in the scanner here in the enterItems() that is in the class as the main class
public void enterItems()
{
int type, quantity, sale,night;
double price;
............................
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
}
So this will pass to the class called Deluxe where i have this method called displayInfo()
public class Deluxe implements Register
{
int quantity,night;
double sale;
public Deluxe(){}
....................................
public double total()
{
double total, price = 200.0;
price = price*quantity*night;
total = price - (price * (sale/100));
total += total *.06;
return total;
}
public void displayInfo(){
if (quantity > 0){
System.out.println("Room Type : Deluxe Room");
System.out.println("Quantity: " +quantity);
System.out.println("Discount: " +sale);
}
}
}
the problem is, in checking for quantity > 0, it actually does not get any value that i put in in the scanner. It will always return 0 for quantity regardless what amount i put in.
But the calculation works fine. Calculation is to calculate how many (quantity) rooms book x night stay x the room's price.
The calculation is also in the same class as the displayInfo() which is in class Deluxe.
So i was wondering what did i do wrong here.
The quantity which you input here:
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
Goes into main(String[] args).quantity that's defined here:
public class Hotel
{
....
public static void main(String[] args)
{
...
int quantity, sale,night;
...
}
The quantity that you check here:
if (quantity > 0){...}
Is a different parameter - it's Deluxe.quantity and is defined here:
public class Deluxe implements Register
{
int quantity,night;
...
}
Those two parameters have no relation. If you want them both to be the same, you need to pass to class Deluxe the main(String[] args).quantity parameter. You can do this via your own constructor under Hotel.main(String[] args), like so:
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
quantity = run.enterItems();
Register deluxe = new Deluxe(quantity,0,0); // entering the default value for the other two parameters like the empty constructor would leave them.
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
if you change your enterItems() function to return the quantity parameter you need, like so:
public int enterItems()
{
int type, quantity, sale,night;
double price;
.........
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
return quantity;
}
Notice, this solves this only for the quantity parameter. if you need more, you might need to return the Deluxe structure from enterItems(). Good luck!

Methods In Java - Void

I am currently learning about methods and using methods. It sometimes confuses my mind when deciding what to put inside the parameters. I have some code where I created three methods and all correspond. What I must do for this program is to display some services and prices and ask the user if he/she would like it. If they say yes, the prices add up until the end of the array. The part I am having trouble with is how to take in the price from main in my third method. I know that I should use a void method because I am not returning anything, just printing out the prices to the user.
Heres my piece of code for this program:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double price = carMaintenance(name);
finalPrice(price);
}
// First Method
public static void make(String name) {
System.out.println("Hello! We will be happy to service your " + name
+ " automobile today!");
}
// Second Method
public static double carMaintenance(String name) {
String[] services = { "Oil Change", "Tire Rotation", "Air Filter",
"Check Fluids" };
double[] prices = { 39.99, 49.99, 19.99, 10.99 };
double Total = 0;
for (int i = 0; i < services.length; i++) {
System.out.println("Do you want a " + services[i] + " for your "
+ name + " " + prices[i] + "? (y/n)");
String answer;
answer = keyboard.nextLine();
if (answer.equals("y"))
{
Total = Total + prices[i];
}
// Third method
public static void finalPrice ( ? )
Specifically this the part I am having trouble with:
// Third method
public static void finalPrice (double price )
The problem is finalPrice is an invalid type for the variabl which is pretty confusing about.
You have to change finalPrice() to accept a double parameter:
public static void finalPrice(double price) { ... }
And pass the value returned by carMaintenance() to finalPrice():
double price = carMaintenance(name);
finalPrice(price);
Note I am assuming you just forgot to paste the rest of the carMaintenance() method. In the end, of course, it should have the return Total statement.
Your second method is lacking a return statement. You can return the total to main and then send it to your third method, as such:
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double finalPrice = carMaintenance(name);
printFinalPrice(finalPrice);
}
//first method code here
public static double carMaintenance(String name) {
//second method code here, plus:
return total;
}
// Third method
public static void printFinalPrice(double finalprice) {
System.out.println("Your final price is " + finalprice);
}
Pass double from carMaintance to finalPrice
double finalPriceDbl = carMaintenance(name);
finalprice(finalPriceDbl);
and accept double as parameter in finalPrice
public static void finalPrice ( double finalPrice );
also you should return value from carMaintenance with return statemenet
return Total;

Java: Running total for a loop and error: missing return statement

I am still new to Java and I can't figure out how to get it to keep a running total. Any suggestions on what I should look up would be awesome. Thank you for your time.
import javax.swing.*;
public class OrderingProducts2
{
public static double main(String[] args)
{
// Number of products
final int NUMBER_OF_PRODUCTS = 5;
//all of the valid values
int[] validValues = {1, 2, 3, 4, 5};
//prices that coralate with the values
double[] prices = {2.98, 4.50, 9.98, 4.49, 6.87};
//Starting total price of order
double total = 0.00;
//Sring for chosing a product to order
String strProducts;
int productOrdered;
//Starting price of unnamed product
double productPrice = 0.00;
//boolean used to validate product
boolean validProduct = false;
//User input of product number
strProducts = JOptionPane.showInputDialog(null,"Enter the product number you want to order or done");
//product number being converted to an integer
productOrdered = Integer.parseInt(strProducts);
//string for getting the quanity
while(productOrdered > -1)
{
String strQuanity;
int productQuanity;
//user input of quanity
strQuanity = JOptionPane.showInputDialog(null,"Enter the amount of product " + strProducts);
//conversion of the quanity to an integer
productQuanity = Integer.parseInt(strQuanity);
//validation and totaling of the price of order
for(int x = 0; x < NUMBER_OF_PRODUCTS; ++x)
{
if(productOrdered == validValues[x])
{
validProduct = true;
productPrice = prices[x];
total = productPrice * productQuanity;
}
}
}
//if there awas a valid out put this message will show
if (validProduct)
JOptionPane.showMessageDialog(null, "The price for product " + productOrdered + " is $" + productPrice + ". The price for your ordered item/items so far is $" + total);
//if output was not valid this message will show
else
JOptionPane.showMessageDialog(null,"Sorry1 - invalid product entered");
Why is the return type for main double?
It should be public static void main(String[] args)
public static double main(String[] args)
according to j.l.s 12.1.4:Invoke Test.main
Java's main() method to execute should be: declared public, static,
and void. It must specify a formal parameter (ยง8.4.1) whose declared
type is array of String. Therefore, either of the following
declarations is acceptable:
So either: public static void main(String[] args)
or, public static void main(String... args)
Again, assuming that you are using public static double main() method then, you must a return double type value:
This is specified in jls-8.4.7 Method body:
If a method is declared to have a return type, then a compile-time
error occurs if the body of the method can complete normally. In other
words, a method with a return type must return only by using a return
statement that provides a value return; it is not allowed to "drop off
the end of its body".
while(productOrdered > -1)
{
// your code
}
I don't see you have updated(decrement or some other opearation) the productOrdered which might cause it to have a value -1. be careful about it. I may want it to be checked with if-else condition.
There are two immediate issues, but it's difficult to know which one is wrong...(or less correct)...
public static double main(String[] args)
Is wrong for one of two reasons. If this is suppose to be you applications main entry point, then it should read...
public static void main(String[] args)
Otherwise Java won't be able to run your application.
If it's not (and it's just some static method you want to run), then you it should have a return statement before it exists. In which case, it's unlikely that you'll be able to run the class until you either provide a implementation of public static double main(String[] args) somewhere to call it...
For example...
public static void main(String[] args) {
OrderingProducts2.main(args);
}
Updated
In order to generate a running tally, you need to provide some kind of exit value from your loop that the user is capable of entering, in you code you're used productOrdered, but you never change that value within the while loop.
A better solution might be to validate the productOrdered before you enter the loop and use productQuanity as the exit value.
In you main loop, you are also not incrementing the total, but you are simply setting it's value...
total = productPrice * productQuanity;
Instead, you could use something like...
total += productPrice * productQuanity;
While will increment the total on each loop...
And finally, a runnable example...
// Number of products
final int NUMBER_OF_PRODUCTS = 5;
//all of the valid values
int[] validValues = {1, 2, 3, 4, 5};
//prices that coralate with the values
double[] prices = {2.98, 4.50, 9.98, 4.49, 6.87};
//Starting total price of order
double total = 0.00;
//Sring for chosing a product to order
String strProducts;
int productOrdered;
//Starting price of unnamed product
double productPrice = 0.00;
//boolean used to validate product
boolean validProduct = false;
//User input of product number
strProducts = JOptionPane.showInputDialog(null, "Enter the product number you want to order or done");
//product number being converted to an integer
productOrdered = Integer.parseInt(strProducts);
for (int x = 0; x < NUMBER_OF_PRODUCTS; ++x) {
if (productOrdered == validValues[x]) {
validProduct = true;
productPrice = prices[x];
}
}
if (validProduct) {
int productQuanity = -1;
do {
//string for getting the quanity
String strQuanity;
//user input of quanity
strQuanity = JOptionPane.showInputDialog(null, "Enter the amount of product " + strProducts);
//conversion of the quanity to an integer
productQuanity = Integer.parseInt(strQuanity);
//validation and totaling of the price of order
if (productQuanity > -1) {
for (int x = 0; x < NUMBER_OF_PRODUCTS; ++x) {
if (productOrdered == validValues[x]) {
validProduct = true;
productPrice = prices[x];
total += productPrice * productQuanity;
}
}
}
} while (productQuanity > -1);
JOptionPane.showMessageDialog(null, "The price for product " + productOrdered + " is $" + productPrice + ". The price for your ordered item/items so far is $" + total);
} else {
JOptionPane.showMessageDialog(null, "Sorry1 - invalid product entered");
}
Your main method should be
public static void main(String[] args){
//no return values
}
The main method should have the following signature, else you would not have an entry point of for your Java application.
public static void main(String[] args) // return type is void and not double
And also, you don't need a while there, it'll just be an infinite loop. Replace it with an if.
if (productOrdered > -1) {

Categories