Void methods cannot return a value -Java - java

I am sure this is a dumb question but i have been at it for quite a bit.. I am trying to create a java program that calculates compound interest based off a user input of years and amount of money. But i keep getting an error that a void method cannot return a value. So i switch the method to a double because thats what will be returned, but than it tells me that a double method must return a double. Even tho im returning a double in the loop... Please help
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
**strong text**
Scanner reader = new Scanner(System.in); //creates scanner
System.out.println("Enter number of years until retirement: "); //asks user to input number of years until retirement
int Years = reader.nextInt();
if (Years <= 0) {
System.out.println("Please enter a valid number"); //if the number of years was invalid, exits the program and asks to enter a valid number
System.exit(0);
}
System.out.println("Enter amount of money able to save annually: "); //asks user how much money they can input
double MoneySaved = reader.nextInt();
reader.close(); //closes scanner
for(int i=0; i < Years; i++)
{
Total = MoneySaved * 1.05;
return Total;
}
System.out.println("You will have $" + df.format(TotalAmount) + " saved up by retirement");
}
}

change your for to this
Double total = 0;
for(int i=0; i < Years; i++) {
total += MoneySaved;
total *= 1.05;
}
System.out.println(total);

Make the method a double and change
double MoneySaved = reader.nextInt();
to
double MoneySaved = reader.nextDouble();
Also I do not see your declaration of 'Total'; make sure that is declared as a double.

First, main Java method must be void and void methods cannot return a value(even compiler tells you that), although you can use a return statement to break execution of the method and return to calling method.
So answering your question, you have to create method that returns double and then just prints it in your main method or do not return anything and just replace
return Total;
with
System.out.println("You will have $" + df.format(Total) + " saved up by retirement");
PS: it looks like you are new to Java, so for a start read some content about Java, for example offical oracle tutorial

Related

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);
}
}
}

How to get a program to run with arrays and methods? [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 4 years ago.
Improve this question
I am having an issue with my homework assignment. When the program runs it keeps asking the user to enter the dealers twice instead of once, also when try to calculate to total commission it wrong, and also total sales can't get it to run.
Sales
commission
$1 - $5,000
8%
More than $5,000 to $15,000
15%
More than $15,000
20%
Problem:
Write a method to input and return the number of dealers. Perform the appropriate data validation here.
Write a method to gather the required input data. Perform the appropriate data validation here.
Write a method to calculate the commission array.
Write a method to calculate and return total sales for the dealership. Totals sales does not include the commission.
Write a method to calculate and return average sales for the dealership. The average sales value does not include the commission.
Write a method to calculate and return the total commission for the dealership.
Write a method to display the dealer name and amount of sales and the amount of commission for all dealers in a tabular format.
Write a method that accepts the name of a dealer as its parameter and returns the amount of commission for the given dealer. If the given name does not exist, issue an error message.
In your main method, make sure to call your methods to perform the operations. MAKE sure to display all the calculated data returned by your methods. For example, the totals and averages must be displayed, so the answers could be checked. Make output descriptive and provide 2 digits after the decimal point for all monetary values.
public static void main(String[] args) {
// TODO Auto-generated method stub
int d = dealers();
int [] numberDealers = new int [dealers()];
String [] employeeInfo = new String[numberDealers.length];
dealerInfo(employeeInfo.length);
getCommission(d);
//dealerTotalSales(employeeInfo.length);
}
//Method to get number of dealers from user input
public static int dealers() {
Scanner input = new Scanner(System.in); // Scanner for user input
System.out.println("Enter the number of dealears: ");
int numberDealers = input.nextInt();//Read user input
//Check to see if user is in range
//While not in range display error message and ask for input again
while(numberDealers < 0 || numberDealers > 20)
{
System.out.println("Invalid number, Please enter a number dealers
from 0 - 20!");
numberDealers = input.nextInt();
}
return numberDealers; //Return number of Dealers
}
public static void dealerInfo(int dealer) {
Scanner input = new Scanner(System.in); // Scanner for user input
String[] dealersName = new String [dealer];
double[] dealerSales = new double [dealer];
for (int i = 0; i < dealer; i++)
{
System.out.println("\nEnter the name of dealer: ");
dealersName[i] = input.next();
System.out.println("\nEnter the sales for dealer: ");
dealerSales[i] = input.nextDouble();
System.out.println("Name " + "Sales");
System.out.println(dealersName[i] + " " + dealerSales[i]);
}
}
public static void getCommission( int totalSales) {
double commission = 0.0;
double commissionRate ;
if( totalSales >0 && totalSales < 5000) {
commission = 0.10;
//System.out.print(commission);
}else if(totalSales < 15000 ){
commission = 0.15;
//System.out.print(commission);
}else {
commission = 0.20;
//System.out.print(commission);
}
commissionRate = commission + totalSales;
System.out.println("\n"+commissionRate );
}
public static double dealerTotalSales(int[] numDealers)
{
double totalSales = 0.0;
for (int i = 0; i < numDealers.length; i++) {
totalSales = totalSales + numDealers[i];
}
return totalSales;
}
}
The reason its asking you to enter the number of dealers two times is because you are calling the dealers() function twice in your main function. you can solve this by replacing
int [] numberDealers = new int [dealers()];
with
int [] numberDealers = new int [d];

Logic error in Recursive method

Im trying to write a program that uses a recursive method to calculate how many months it will take to reach a goal of 10 million total invested if the same amount of money(inputted by the user) is invested with a 2 percent interest added each month. The problem is the method is returning counter too early so my "months" output is inaccurate. My guess is that my last else statement is wrong or my counter is placed incorrectly
Heres my code
import java.util.Scanner;
public class MoneyMakerRecursion {
public static int counter = 0;
public static void main(String[] args) {
//Variables declared
Scanner userInput = new Scanner(System.in);
double investment;
//User is prompted for input
System.out.println("Enter your monthly investment: ");
investment = userInput.nextInt();
//Method is called
Sum(investment);
//Results from recursive method output
System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
}
//recursive Method
public static double Sum(double investment) {
counter++;
double total = (investment * 0.02) + investment;
if(total >= 10000000) {return counter;}
else {return Sum(investment+total);}
}
}
Important point you missed is that your monthly investment is same throughout all months. Hence it should be static variable.
Second point you were adding investment to total which was local variable to that method. Which is not a actual investment for month. its a value passed to that function which changes for each month(Consider your code for this statement)
See below working code.
import java.util.Scanner;
public class MoneyMakerRecursion {
public static int counter = 0;
public static double investment = 0;
public static void main(String[] args) {
//Variables declared
Scanner userInput = new Scanner(System.in);
//User is prompted for input
System.out.println("Enter your monthly investment: ");
investment = userInput.nextInt();
//Method is called
Sum(investment);
//Results from recursive method output
System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
}
//recursive Method
public static double Sum(double totalInvestment) {
counter++;
double total = (totalInvestment* 0.02) + totalInvestment;
if(total >= 10000000) {return counter;}
else {return Sum(total+investment);}
}
}
Result
Enter your monthly investment:
100000
It should take 55 month(s) to reach your goal of $10,000,000
Here is snapshot: here interest is considered annually hence converting 0.02 monthly interest to per year interest it becomes 0.24

Java Averaging Program

Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
 A method that accepts two integer parameters and returns their average.
 A method that accepts three integer parameters and returns their average.
 A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.

Am I doing something wrong with my try-catch block?

So we have to make a mortgage calculation project where we have to ask the user to calculate again and now we have to make it so it prints out a error message every time the user enters a string value for any of the inputs. I thought I did it right but something strange happens every time I run it and I can't figure out why and I know it's something wrong with the Try-Catch blocks.
Here are my outputs: http://imgur.com/cbvwM5v
As you can see the third time i run the program I enter a "two" as the second input and it still did the calculations. Then, the third time I tried it, I entered a negative number then a "two" and everything worked the way I wanted it to. Then, the last time I ran it I put a positive number for the first input and it still did the calculations, anything you guys see that might be doing this? Also, I think I may have used the wrong exception, I'm not uite sure what it means, I just guessed. am I supposed to user NumberFormatException and there is also a line under nfe saying that the value is not being used.
Here's my code:
package MortgageCalculation2c;
import java.text.NumberFormat;
import java.util.Scanner;
/**
*
* #author Akira
*/
public class MortgageCalculation2c {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double loanAmount = 0;
double interestRate = 0;
double numberYears = 0;
double months;
double monthlyPayment;
double numerator;
double denominator;
double formula;
boolean userInput = true;
String answer = ("y");
while (userInput) {
try {
loanAmount = 0;
interestRate = 0;
numberYears = 0;
//prompt user for the loan amount
System.out.print("Enter the loan amount: ");
loanAmount = Double.parseDouble(in.nextLine());
//prompt the user for the interest rate
System.out.print("Enter the rate: ");
interestRate = Double.parseDouble(in.nextLine());
//prompt the user for thenumber of years
System.out.print("Enter the number of years: ");
numberYears = Double.parseDouble(in.nextLine());
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
}
//if the user enters a negative number print out a error message, if not, continue calculations
if ((loanAmount <= 0) || (interestRate <= 0) || (numberYears <= 0)) {
System.out.println("ALL NUMERICAL VALUES MUST BE POSITIVE!");
} else {
//convert the interest rate
interestRate = interestRate / 100 / 12;
//the number of years must be converted to months
months = numberYears * 12;
//numerator of the monthly payment formula
numerator = (Math.pow(1 + interestRate, months));
//denominator of the monthly payment formula
denominator = ((numerator)-1);
//the formula equals the numerator divided by the denominator
formula = ( numerator / denominator );
//monthly payment calculation
monthlyPayment = (interestRate * loanAmount * formula);
//sytem output
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
System.out.println("The monthly payment is: " + defaultFormat.format(monthlyPayment));
}
//prompt the user if they would like to calculate the program again.
System.out.println("Would you like to calculate again (y/n) : ");
//if the user enters "y" the program will run again and if the user enters anything else it ends
answer = in.nextLine();
answer = answer.toLowerCase();
if ( answer.equals("y")){
userInput = true; //tests the program if it needs to run again
}else{
break; //ends the program
}
}
}
}
Is there anything that you guys can see that might be the problem?
It seems you need continue in your catch block, so the program flow goes back to the loop.
...
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
continue; // <---------- here
}
...
If this is not a specific exercise in try-catch construct, it be would be better to use Scanner's method hasNextDouble() for validatiing and nextDouble for reading and converting the numbers.
It will look something like this:
//prompt user for the loan amount
loanAmount = enterPositiveDouble("Enter the loan amount: ")
//prompt the user for the interest rate
interestRate = enterPositiveDouble("Enter the rate: ");
//prompt the user for the number of years
numberYears = enterPositiveDouble("Enter the number of years: ");
and you will have a special static method enterPositiveDouble like following:
static void enterPositiveDouble(String prompt) {
Scanner in = new Scanner(System.in);
boolean ok = true;
double result = -1;
do {
System.out.print(prompt);
ok = (in.HasNextDouble() && (result = in.NextDouble()) > 0)
if ! ok
System.out.println("You must enter positive numerical data!");
} while (!ok);
}
The above is not an optimal code but just the illustration of a possible solution.

Categories