Methods In Java - Void - java

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;

Related

Absolute java beginner. I cannot use a returned variable

This assignment is to calculate the cost of a hospital visit. I am trying to ask the user what the prices for the "overnightCharge", "medicationCharge", and "labCharge" are. I then try to use the input to add them together in the method called "total". Next, I try to print the resulting/returned variable from "total" method in the main method by typing System.out.println("Your total charge is: " + total(totalCost). I thought total(totalCost) would retrieve the variable returned by "total" method.
package hospitalstay;
import java.util.Scanner;
/* total charges
if overnight charges
medication charges
lab charges
ask user if new patient*/
public class HospitalStay {
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
public static double overnightCharge () {// asking user for overnight charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your overnight charge");
double overnightCharge;
overnightCharge = sc.nextDouble();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your medication charge");
double medicationCharge;
medicationCharge = sc.nextDouble();
return medicationCharge;
}
public static double labCharge() {//asking user for lab charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your lab charge");
double labCharge;
labCharge = sc.nextDouble();
return labCharge;
}
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
double totalCost;
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicineCharge + labCharge); //Calculating all three charges
}
else {
totalCost = (medicineCharge + labCharge);
}
return totalCost;
}
}
You have changeŠ² the total method to
public static double total () {
return overnightCharge() + medicineCharge() + labCharge();
}
Also change main method to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total());
}
First of all, you've defined three parameters for method "total," but you are specifying only one argument in your main method:
total(totalCost)
to minimize the number of things that you need to change in your code, I would simply change the total() method to:
public static double total() {
double totalCost = overnightCharge();
totalCost += medicationCharge();
totalCost += labCharge();
return totalCost;
}
and in your main method:
public static void main(String[] args) {
System.out.println("Your total charge is: " + total();
}
You are passing the wrong inputs to total, change your main to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(medicationCharge(), labCharge(), overnightCharge()));
}
Also, in your total method, you don't need the if condition, so you can simplify it to:
public static double total(double medicineCharge, double labCharge, double overnightCharge) {
return (overnightCharge + medicineCharge + labCharge);
}
"Explanation why your code didn't work as desired: "
You have created a function total() which takes 3 arguments i.e (double medicineCharge, double labCharge, double overnightCharge)
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
return totalCost;
}
But when you are calling this function in your main() you are only passing it a single argument that is total(totalCost).
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
You have also made a typo mistake "medicineCharge"
You can try something like this to achieve your desired output :
import java.util.Scanner;
public class Hospital {
static Scanner input;
private static double overnightCharge, medicationCharge, labCharge,
totalCost;
public static double takeInput() { // single function to take input
input = new Scanner(System.in);
return input.nextDouble();
}
public static double overnightCharge() {// asking user for overnight charge
System.out.println("What is your overnight charge");
overnightCharge = takeInput();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication
// charge
System.out.println("What is your medication charge");
medicationCharge = takeInput();
return medicationCharge;
}
public static double labCharge() {// asking user for lab charge
System.out.println("What is your lab charge");
labCharge = takeInput();
return labCharge;
}
public static double total() {
overnightCharge();
medicationCharge();
labCharge();
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicationCharge + labCharge); // Calculating
// all
// three
// charges only when overnightCharge = 0
} else {
totalCost = (medicationCharge + labCharge);
}
return totalCost;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Total :" + total());
}
}
Note: I have also reduced the code for calling scanner again again.

Meaning and how to get and work with a return value from a user input in a method in java

I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}

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

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"
}
}

How do I use the return value from a method in another method different from the calling method?

I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());

How to work around using multiple scanners

I have a a program that is suppose to take information on the speed of the computer, how much ram the computer has, etc etc(Basically a computer inventory system). Nothing is really wrong with the program as far as I know. The only problem I have is that I do not want to use multiple scanner since I've read it's considered bad practice. The scenario is I have the main method, public static void main, acting as a menu system(The user simply inputs the choice that he wants). Then there are other methods that asks information like how fast is your computer, how much ram does your computer, or even if you would like to remove a computer from your inventory system. Each of these methods have a scanner object and I want to know how I can trim it down to one scanner that could interact with all the data.
Update: Here is a the complete program of the program.
package computerinventory;
import java.util.Scanner;
import java.util.ArrayList;
public class ComputerInventory
{
private static Scanner read = new Scanner(System.in);
public static void main(String[] args)
{
ComputerInventory process = new ComputerInventory();
ArrayList<Computer> computer = new ArrayList<>();
int option;
do
{
System.out.println("1.) Add computers to your inventory.");
System.out.println("2.) Display your Inventory.");
System.out.println("3.) Remove Computers from your inventory.");
System.out.println("4.) Quit the program. ");
option = read.nextInt();
switch(option)
{
case 1:
process.addComputers(computer);
System.out.println("");
break;
case 2:
process.displayInventory(computer);
System.out.println("");
break;
case 3:
process.removeComputer(computer);
break;
case 4:
System.out.println("\nThank you for using my program.");
return;
default:
System.out.println("\nThis choice doesn't exist in the menu.");
}
}
while(true);
}
public void addComputers(ArrayList<Computer> computer)
{
double computerSpeed;
int hardDrive;
double ram;
boolean functional;
double cost;
System.out.println("\nHow fast is this computer in Ghz?");
computerSpeed = read.nextDouble();
System.out.println("\nHow big is the HardDrive in GB?");
hardDrive = read.nextInt();
System.out.println("\nHow much ram does this computer has. ");
ram = read.nextDouble();
System.out.println("\nTrue or false, does this computer work?");
functional = read.nextBoolean();
System.out.println("\nHow much does this computer cost? ");
cost = read.nextDouble();
Computer com = new Computer(computerSpeed, hardDrive, ram, functional, cost);
computer.add(com);
}
public void displayInventory(ArrayList<Computer> computer)
{
for (Computer computer1 : computer)
{
System.out.println(computer1);
}
}
public double totalCost()
{
return 0;
}
public void removeComputer(ArrayList<Computer> computer)
{
}
}
package computerinventory;
public class Computer
{
private double computerSpeed;
private int hardDrive;
private double ram;
private boolean functional;
private double cost;
public Computer(double computerSpeed, int hardDrive, double ram, boolean functional, double cost)
{
this.computerSpeed = computerSpeed;
this.hardDrive = hardDrive;
this.ram = ram;
this.functional = functional;
this.cost = cost;
}
public Computer()
{
}
public void setComputerSpeed(double computerSpeed)
{
this.computerSpeed = computerSpeed;
}
public void setHardDrive(int hardDrive)
{
this.hardDrive = hardDrive;
}
public void setRam(double ram)
{
this.ram = ram;
}
public void setFunctional(boolean functional)
{
this.functional = functional;
}
public void setCost(double cost)
{
this.cost = cost;
}
#Override
public String toString()
{
return "\nSpeed is " + computerSpeed + " GHz.\n" + "hardDrive is " + hardDrive
+ " GigaBytes.\n" + "RAM is " + ram + "GigaBytes.\n" + "Status is " + functional
+ "\n" + "The cost of this computer " + cost;
}
}
You can use the Scanner method in the main class and possibly prompt for inputs in the main class.
public static void main(String[] args)
{
// Scanner object created here
// Ask for information here, variables a and b
// ArrayList that is suppose to contain all the information.
// menu here with four choices
}
public void doSomething(ArrayList<ClassName> obj, int a, int b)
{
// Add paramater variables to the existing array list
}
// More methods as you go down with a scanner object.
Here I use one scanner to gather all of the data, if you'd like, I can post an update at your request passing the scanner to the method also. This same practice works with pretty much any data type. You can expand on this to use ArrayLists, which would be pretty easy also.
try this code out:
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
int data1;
int data2;
int data3;
System.out.println ("Enter data1: ");
data1 = input.nextInt(); //Can use .nextDouble/float/long/short/byte/line/char... ();
System.out.println ("Enter data2: ");
data2 = input.nextInt();
data3 = manipData (data1, data2);
System.out.println (data1 + " + " + data2 + " = " + data3);
input.close(); // Be sure to close your scanner
}
public static int manipData (int data1, int data2) {
return data1 += data2;
}
Declare the Scanner at level class as a static field. In this way, you have a single Scanner instance available to all the methods of this class and available for other classes as well.
public class X {
public static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
//...
foo();
//...
scanner.close();
}
public static void foo(...) {
System.out.println("Please enter the value of x:");
int x = scanner.nextInt();
System.out.println("The result of working with X: " + realMethod(x));
}
public static int realMethod(int x) {
int result = ...; //some operations done with an X parameter
return result;
}
}

Categories