calling methods, parameters and arguments - java

This is probably a dumb question. My following code looks fine but on the output, it does not expect results from my testing scenarios. Code follows:
import java.util.Scanner;
public class PartyPlannerLab {
public static Scanner input = new Scanner(System.in);
public static int getGuestCount(int guests) {
while(true) {
System.out.print("Enter number of guests: ");
guests = input.nextInt();
if (guests >= 1 && guests <= 100)
break;
else
System.out.println("The guest count must be at least 1, but does not exceed 100. Please enter again.");
}
return guests;
}
public static int getSlicesPerPerson(int slicesPerPerson) {
while(true) {
System.out.print("Enter number of slices per person: ");
slicesPerPerson = input.nextInt();
if (slicesPerPerson >= 1 && slicesPerPerson <= 8)
break;
else
System.out.println("The pizza slice count must be at least 1, but does not exceed 8. Please try again.");
}
return slicesPerPerson;
}
public static double computeRoomCost(int guests, double roomCost) {
if (guests <= 30)
roomCost = 100.00;
else
roomCost = 200.00;
return roomCost;
}
public static double computeSodaCost(double sodaCost, int guests) {
sodaCost = guests * 1.50;
return sodaCost;
}
public static void printSummary(int guests, double roomCost, double sodaCost, double pizzaCost) {
System.out.println("Total Guests: " + guests);
System.out.println("RoomCost: $" + roomCost);
System.out.println("SodaCost: $" + sodaCost);
System.out.println("PizzaCost: $" + pizzaCost);
System.out.println("Total Cost: $" +(roomCost + sodaCost + pizzaCost));
}
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
getGuestCount(guests);
getSlicesPerPerson(slicesPerPerson);
computeRoomCost(guests, roomCost);
computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
}
One output is as follows:
Enter number of guests: 10
Enter number of slices per person: 2
Total Guests: 0
RoomCost: $0.0
SodaCost: $0.0
PizzaCost: $0.0
Total Cost: $0.0

You are not making use of the return values of getGuestCount, getSlicesPerPerson etc.
Those methods return a value, which basically means that you can use them as if they are a value. input.nextInt returns a value too, which is why you can put it on the right of =.
Inside the method, getGuestCount seems to change the value of guests passed in, but this change won't actually reflect on the caller's side, because Java is pass-by-value. You are kind of throwing away the value that was passed in.
In fact, your methods will only work as they are if the arguments are passed by reference, so that the methods can modify the variables passed in. But this is not possible in Java. See this post for the difference between pass-by-value and pass-by-reference.
The right way to rewrite your methods in Java is to return the value (which they are already doing, but you are not making use of the return value), and remove the extraneous parameter.
public static int getGuestCount() {
int guests;
while(true) {
System.out.print("Enter number of guests: ");
guests = input.nextInt();
if (guests >= 1 && guests <= 100)
break;
else
System.out.println("The guest count must be at least 1, but does not exceed 100. Please enter again.");
}
return guests;
}
public static int getSlicesPerPerson() {
int slicesPerPerson;
while(true) {
System.out.print("Enter number of slices per person: ");
slicesPerPerson = input.nextInt();
if (slicesPerPerson >= 1 && slicesPerPerson <= 8)
break;
else
System.out.println("The pizza slice count must be at least 1, but does not exceed 8. Please try again.");
}
return slicesPerPerson;
}
public static double computeRoomCost(int guests) {
double roomCost;
if (guests <= 30)
roomCost = 100.00;
else
roomCost = 200.00;
return roomCost;
}
public static double computeSodaCost(int guests) {
double sodaCost = guests * 1.50;
return sodaCost;
}
This is how you "make use of the return values": instead of passing in the variable you want the method to modify, put it on the left hand side of = in an assignment statement:
guests = getGuestCount();
slicesPerPerson = getSlicesPerPerson();
roomCost = computeRoomCost(guests);
sodaCost = computeSodaCost(guests);

The reason why you are not getting the output is that the values that you initialized in your main method are not being updated with the method calls you are making.
Below code might solve the problem you are facing -
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
guests = getGuestCount(guests);
slicesPerPerson = getSlicesPerPerson(slicesPerPerson);
roomCost = computeRoomCost(guests, roomCost);
sodaCost = computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
Note- There is no need of passing the parameter in the methods getGuestCount & getSlicesPerPerson as the input is being taken from I/O

Related

Trying to figure out how to pass array object data to a separate method

I wanted to write a program that records bar inventory as I'm a bartender. I can't figure out how to pass the liquorCost and liquorCount data to the GetCostTotal() method below the main() method. I'm absolutely sure it's something fairly straightforward that I'm doing incorrectly but I just can't figure it out. Any help is appreciated.
My Liquor class is separate and I can post that if necessary but I don't think it's the class that's giving me the problem, it's retrieving the data input from the array to the separate method.
package inventory;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (liquorCost * liquorCount);
}
return costTotal;
}
}
try this
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(inv);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (inv[i].getLiquorCost() * inv[i].getLiquorCount());
}
return costTotal;
}
Lets understand what went wrong here.Take a look at how you are trying to call the GetCostTotal() method.
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
This is incorrect. The syntax/way you are calling the method is actually used when we what to define a method. Like you did:
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {}
Your call should be like:
double costTotal = GetCostTotal(inv);
Here, we are passing only inv because the data for liquorCost and liquorCount is available inside "each" element of array inv.
Now you can accept this argument in GetCostTotal method. Here as you are iterating using a for loop, you can read the data you needed as inv[i].getLiquorCost() and inv[i].getLiquorCount().
I suggest you can read more on defining a method and calling a method in java.

returning a void method in my main method

My question is based on returning a Void method on my main method in java the following its my code. Where am I doing wrong?
package practiceq3;
import java.util.Scanner;
public class Practiceq3 {
public void FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
{
System.out.printf("%-5s %s \n", "Years", "Investment Value");
//For loop
int i;
int y;
for(i = 1; i <= Years; i++)
{
for (y = 1; y <= 12; y++)
{
InvestmentAmount += (InvestmentAmount * MontlyInvestmentRate);
System.out.printf("%-5d %2f \n", i , InvestmentAmount);
}
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the Investment Amount: ");
double InvestmentAmount = input.nextDouble();
System.out.print("Enter the Montly investment rate: ");
double MontlyInvestmentRate = input.nextDouble();
System.out.print("Enter the Years: " );
int Years = input.nextInt();
Practiceq3 m = new Practiceq3();
// Compilation error here:
System.out.printf("Investment Value is $%2f", m.FutureInvestmentValue(input.nextDouble(),(input.nextDouble()/1200), Years));
input.close();
}
}
The compilation fails with the error:
Error:(34, 78) java: 'void' type not allowed here
Your method FutureInvestmentValue doesn't return any value, but you are trying to print the (missing) return value from this method:
System.out.printf("Investment Value is $%2f", m.FutureInvestmentValue(...));
Looking over your code, it's not quite clear how exactly should the method FutureInvestmentValue behave - it seems to print the calculated information itself.
Probable solutions would be either:
System.out.println("Investment Value is:");
m.FutureInvestmentValue(...); // Prints the calculated data itself
Leave the System.out.printf line in the main method unchanged and modify the FutureInvestmentValue to return some value instead of printing it.
You'll need to do one of two things: either return the result from your method or instead of return value, print out the method parameter that you used to store the result.
So either change your FutureInvestmentValue method like this:
public double FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
{
// skip other stuff
return InvestmentAmount;
}
or change your main method to something like this:
double value = input.nextDouble();
m.FutureInvestmentValue(value, value/1200, Years);
System.out.printf("Investment Value is $%2f", value);
As mentioned by Alex FutureInvestmentValue method is void and hence you are getting error. If you want to print theinvestmentValue in print statement then change the return type of method to double and return InvestmentAmount variable value.
i managed to answer this question the way the question requested but i also considered what you guys said and at the end i managed to see my mistakes in my code so the following is my answer for the question
import java.util.Scanner;
public class ClassA {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
ClassB con = new ClassB();//this is the object of the class
System.out.print("Enter the Investment Amount: ");
double investmentAmount = input.nextDouble();
System.out.println();
System.out.print("Enter the Montly investment rate: ");
double montlyInvestmentRate = input.nextDouble();
System.out.println();
System.out.print("Enter the Years: ");
int years = input.nextInt();
System.out.println();
//this is where we call our void method FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
con.FutureInvestmentValue(investmentAmount ,(montlyInvestmentRate/1200), years);
}
}
}
public class ClassB {
public void FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
{
System.out.printf("%-5s %s \n", "Years", "Future Value");
//For loop
int i;
double Fv;
for(i = 1; i <= Years; i++)
{
//Future value formular A=P(1+i/m)^n*m
Fv = (InvestmentAmount * Math.pow(1+MontlyInvestmentRate,i*12));
System.out.printf("%-5d %.2f \n", i , Fv);
}
}
}

Method calculations/arguments in Java

I have to create a virtual coffee shop where the user enters their order number, how many of that order they want, calculate the subtotal and the discount, etc. The whole point of this is that the process's divided into various methods. Most of the methods are pretty simple, but I'm having trouble with the computeSubTotal method. I have to initialize subtotal in the main method to make this work, but when the subtotal's calculated in computeSubTotal, it always ends up being zero. Sorry if this seems stupid, but I have no idea what I'm doing wrong, help?
import java.util.Scanner;
public class CoffeeShopWithMethods
{
public static void main(String[] args)
{
Scanner user_input = new Scanner (System.in);
String user_name;
System.out.print("\nPlease enter your name: ");
user_name = user_input.next();
System.out.println("\nWelcome to the Java Byte Code Coffee Shop, " + user_name + "!");
int orderNumber = 0;
int orderQuan = 0;
double subTotal = 0.0;
//Beginning of calls to methods
displayMenu();
getItemNumber(orderNumber);
getQuantity(orderQuan);
computeSubTotal(orderNumber, orderQuan, subTotal);
discountCheck(subTotal);
}
public static void displayMenu()
{
System.out.println("\nHere is our menu: \n" + "\n 1. Coffee $1.50" + "\n 2. Latte $3.50" + "\n 3. Cappuccino $3.25" + "\n 4. Espresso $2.00");
}
public static int getItemNumber(int orderNumber) //prompts user for item number (1 for coffee, 2 for latte, etc...)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the item number: ");
orderNumber = user_input.nextInt();
final double Coffee = 1.50;
final double Latte = 3.50;
final double Cappuccino = 3.25;
final double Espresso = 2.00;
double Cost = 0;
if (orderNumber == 1)
Cost = Coffee;
if (orderNumber == 2)
Cost = Latte;
if (orderNumber == 3)
Cost = Cappuccino;
if (orderNumber == 4)
Cost = Espresso;
return orderNumber;
}
public static int getQuantity(int orderQuan)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the quantity: ");
orderQuan = user_input.nextInt();
return orderQuan;
}
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
public static boolean discountCheck(double subTotal) //takes subtotal and returns true if user earned a discount (over $10)
{
if (subTotal >= 10.00)
return true;
else
return false;
}
}
Your methods getItemNumber, getQuantity, computeSubTotal and discountCheck all return a value, but you are not storing that return value in your main method.
In addition to that, your getItemNumber() method is only storing the cost locally, which is then discarded when the method is finished - the cost should be returned (and the method probably renamed).
You probably should have something like this:
//Beginning of calls to methods
displayMenu();
double itemCost = getItemCost(); // was getItemNumber()
orderQuan = getQuantity(orderQuan);
subTotal = computeSubTotal(itemCost, orderQuan);
boolean shouldDiscount = discountCheck(subTotal);
Of course, to use an object-oriented approach, the variables should be members of your class, then you wouldn't need to pass or return values - they would be accessible to all methods in the class.
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
In your computeSubTotal method, you do
subTotal = (orderNumber * orderQuan);
This is not going to intiailize the variable in the main method; you are re-initializing the parameter variable.
In your main method, you should be doing
subTotal = computeSubTotal(orderNum, orderQuan);
instead of calling the method without using the return value. You might have noticed that I didn't pass subTotal to the method. This is not needed. You can instead re-declare the variable inside the method:
public static double computeSubTotal(int orderNumber, int orderQuan)
{
double subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
This applies to the other variables aswell. Java is pass-by-value, so if you pass a value to a method, a new reference is created for the method (when you do int varName in your method's parameters when you declare the method)

using scanner class to average numbers in java

I am using a scanner class to average numbers together. I am using a method to do the averaging. I do not want the program to run if there are more than 20 args. I cant seem to get this to work. I am very new at java and trying to learn.
I appreciate any help I can get. Thanks!
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x = 0.00d;
if (args != null) {
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
x = scan.nextInt();
if (x <= 21) {
System.out.println("Please do not add more than 20 numbers");
}
} else {
}
}
public double average(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Just run a while loop that breaks when 20 "args" is met or until a break like -1 is entered. Then if you are taking double values, you should use x = scan.nextDouble(). You also do not have a place where you are inserting the values into your array. At the end of your while loop you could put x into an array of doubles.
private double x;
private double Foo[] = new Foo[20];
private int this = 0; //Your counter
while(this < 20 && x != -1)
{
x = scan.nextDouble();
Foo[this++] = x;
}
Then carry out your public double Average by adding up the values in the array and dividing by (double)this
Here is a solution (cleaning up a lot of your code as well) that gets all the numbers on one line after the start of the program:
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double values[] = new double[20];
int count = 0;
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
String inputs = scan.nextLine();
scan = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan.hasNextDouble())
{
if(count == 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
values[count] = scan.nextDouble();
count += 1;
}
System.out.println("Your average is: " + average(values, count));
}
public static double average(double [] values, int count) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= count;
return average;
}
}
I got thinking you might want to use the args that are passed to main, since you use a null check, so you want to run your program like this:
java programTwo num1 num2 num3 num4 num5
etc. If that's the case, we have another solution:
class programTwo {
public static void main (String[] args) {
if(args.length > 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
double values[] = new double[args.length];
for(int i=0; i< args.length; ++i)
values[i] = Double.valueOf(args[i]);
System.out.println("Your average is: " + average(values));
}
public static double average(double [] values) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= values.length;
return average;
}
}
The args != null check is unnecessary. One way to accomplish what you want is to accept numbers while the scanner has a next number (scanner.hasNext() perhaps) and break if the number of inputs thus far is less than 20. Since the number of double numbers is unknown, you're better off using an ArrayList.
List<Double> doubles = new ArrayList<Double>();
and calling the add method on doubles
doubles.add(x);
Then pass this to a method that averages the values in the arraylist.

Finding an average of a loop from a different method?

I am in the middle of an exercise on arrays and I am currently stuck on one of the variations in which
I have to use an Array (no arraylists) to gather user input with a
max number of 100 inputs and the inputs must stop if a negative
number is inserted.
The program then prints each value input by the user on a separate
line with the "Above", "Below", or "EqualTo" relating to the average
of the inputs.
Issue :- I am currently stuck in how I am supposed to get the value of the inputs from the load method into the correct spots on the print method. The program will compile but will only return an average1 equal to zero. Any help is appreciated, I just can't use an arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}
That's because you are not saving the average to the global variable average1 but to a local variable. That is why average1 returned by getAverage() equal to zero.
Change the below line in load() method from
double average1 = sum / used;
to
average1 = sum / used;

Categories