How do i calculate a whole bunch of different scanner inputs? - java

I'm not quiet sure how to go about doing the calculations for this. I have everything down right up until i'm trying to actually get the investment amount. I know what i have right now is wrong, but google isn't being super helpful for me, and my book just does not have what i need in order to complete this darn thing.
Here what i have right now
import java.util.Scanner;
class InvestmentCalculator {
public static void main(String[] args) {
// create a scanner object
Scanner input = new Scanner(System.in);
// Prompt user to enter investment amount
Scanner amount = new Scanner(System.in);
System.out.println("Enter Investment Amount");
while (!amount.hasNextDouble()) {
System.out.println("Only Integers");
amount.next();
}
//Promt user to enter interest rate
Scanner interest = new Scanner(System.in);
System.out.println("Enter Interest Percentage in decimals");
while (!interest.hasNextDouble()) {
System.out.println("Just like before, just numbers");
interest.next();
}
//Prompt user to enter number of years
Scanner years = new Scanner(System.in);
System.out.println("Enter Number of Years");
while (!years.hasNextDouble()) {
System.out.println("Now you are just being silly. Only Numbers allowed");
years.next();
}
//Compute Investment Amount
double future = amount * Math.pow((1 + interest), (years * 12));
//Display Results
System.out.println("Your future investment amount is " + future);
}
}
Any assistance would be very very helpful!

First of all amount, interest and years are Scanners, they are not numbers. The Scanner could contain any number of different types of content so it's impossible for something like Math.pow to know what it should do with them
You need to assign the values you read from the user to some variables.
I'd start by using a single Scanner, say called kb...
Scanner kb = new Scanner(System.in);
Then use this whenever you want to get a value from the user...
You input loops seem wrong to me, I'm not particularly experienced with the Scanner, so there is probably a better way to achieve this, but...
int invest = -1; // amount
double rate = -1; // percentage
int period = -1; // period
do {
System.out.println("Only Integers");
String text = kb.nextLine();
try {
invest = Integer.parseInt(text);
} catch (NumberFormatException exp) {
System.out.println("!! " + text + " is not an integer");
}
} while (invest == -1);
System.out.println(invest);
Once you have all the information you need, make your calculations with these primitive types...
double future = invest * Math.pow((1 + rate), (period * 12));

You don't have to use 4 different scanners for this because you are reading from the same stream.... Your code should be something like this -
import java.util.Scanner;
class InvestmentCalculator {
public static void main(String[] args) {
double amount=0;
int interest=0;
double years=0;
// create a scanner object
Scanner input = new Scanner(System.in);
// Prompt user to enter investment amount
Scanner amount = new Scanner(System.in);
System.out.println("Enter Investment Amount");
while (!input.hasNextDouble()) { // you say you only want integers and are
// reading double values??
System.out.println("Only Integers");
amount = input.nextDouble();
}
//Promt user to enter interest rate
System.out.println("Enter Interest Percentage in decimals");
while (!input.hasNextInt()) {
System.out.println("Just like before, just numbers");
interest= input.nextInt();
}
//Prompt user to enter number of years
System.out.println("Enter Number of Years");
while (!input.hasNextDouble()) {
System.out.println("Now you are just being silly. Only Numbers allowed");
years=input.nextDouble();
}
//Compute Investment Amount
double future = amount * Math.pow((1 + interest), (years * 12));
//Display Results
System.out.println("Your future investment amount is " + future);
}
}

Related

How can I make this code stop after the first input

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter your salary per hour: ");
int salary = input.nextInt();
System.out.print("Enter number of hours: ");
int hours = input.nextInt();
int sum = salary * hours;
if (hours == 0) {
System.out.println("Stop!");
break;
}
System.out.println("Total salary " + sum);
}
}}
I want to be able to enter numbers until I press 0, and then I want the program to stop. It stops after two zeros, but how can I make it stop after pressing only one zero? I have tried this while-if loop and different do-while loops, I just can't make it work.
Your code does exactly what you tell it to do.
You tell it to:
first ask for TWO numbers
to then compare the first number, and stop on 0
So, the solution is:
ask for one number
compare the number, stop on 0
ask for the second number
If you want to exit whenever you type 0, then you have to check every value after its input.
There is the code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("What's your salary per hour? ");
int salary = scanner.nextInt();
if (salary == 0)
exit();
System.out.print("How many hours did you worked today? ");
int hours = scanner.nextInt();
if (hours == 0)
exit();
int sum = salary * hours;
System.out.println("Your total salary is " + sum);
}
}
private static void exit() {
System.out.println("Have a nice day!");
System.exit(0);
}
Please write a comment if that doesn't match your expectation

How do you call a method with parameters from main method if statement?

I am trying to call the method gasCost from the main method. I give the user the choice of entering a number to bring up a certain calculation, in this instance the user has selected option 3. The integer gallons_Gas is defined in the main method, so I am passing that into gasCost method.
I get an error after the else statement and can't compile. Says .class expected where the variable name gallons_Gas starts and after gallons_Gas says ; expected. What am I doing wrong and how do I fix this?
public class Deryck_HW2_TripCalculatorMenu
{
public static void main(String[] args)
{
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask for gallons of gas consumed
System.out.print("Gallons of Gas Consumed: ");
//Save gallons of gas consumed
int gallons_Gas = userInput.nextInt();
//Give user options menu
menu();
//Ask user choice
System.out.print("Choose from options above (enter number 1-4): ");
//Get user choice 1-4
int choice = userInput.nextInt();
//Test choice
if (choice == 1)
{
//avgSpeed();
}
else if (choice == 2)
{
//mpg();
}
else if (choice == 3)
{
gasCost(int gallons_Gas);
}
else
{
System.out.print("Error: selection invalid. Restart program and enter a number between 1 and 4.");
}
}
public static void gasCost(int gallons_Gas)
{
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask cost of gallon of gas
System.out.print("What is the cost per gallon of gas? ");
//Save cost per gallon
double gallon_Cost = userInput.nextDouble();
//Calculate total cost
double total_cost = (gallons_Gas * gallon_Cost);
System.out.print("Total cost of gas for this trip was $" + total_cost);
}
Try to understand what these lines mean and note how to call methods, how to pass in variables, when to declare variables etc...
import java.util.Scanner;
public class GasCalculator {
public static void main(String[] args) {
final int GALLONS_GAS = 100; // change this to whatever. It's good practice to use constants for variables that does not need to be immuted.
Scanner sc = new Scanner(System.in);
int user_choice = -1;
try {
user_choice = sc.nextInt();
} catch (Exception e) {
System.out.println("Only enter integers.");
main(args);
return;
}
switch(user_choice) {
case 1:
// do something.
break;
case 2:
// do something.
break;
case 3:
gasCost(GALLONS_GAS);
break;
default:
System.out.println("Bad input");
main(args);
break;
}
sc.close();
}
public static void gasCost(int gallons_Gas) {
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask cost of gallon of gas
System.out.print("What is the cost per gallon of gas? ");
//Save cost per gallon
// should try using a try-catch here to handle InputMismatchException
double gallon_Cost = userInput.nextDouble();
//Calculate total cost
double total_cost = (gallons_Gas * gallon_Cost);
System.out.print("Total cost of gas for this trip was $" + total_cost);
userInput.close();
return;
}
}
I don't know if this is a pseudo-code or just the real code. If it is the real code, there are several mistakes:
gasCost(int gallons_Gas);
You should know the differences between formal parameters and actual parameters. In the actual parameters type of variable is not required, instead of formal parameters. Link:
What is a formal parameter in Java?
So, that code should be like:
int gallons_gas = 5; //Just for example
gasCost(gallons_Gas);
After that, you should listen to the guys in the comments: be sure where that else if statement is, if you put it in the wrong way it won't work.
Hope it helps
gasCost(int gallons_Gas);
should be
int gallons_Gas;
if (...) {
gasCost(gallons_Gas);
}
You cannot declare an int within the parameter list of a method call.

why does my scanner(system.in) run twice

I am new to java, been self teaching for the last week. I cannot find the reason why the if else statement runs twice. here is the whole code, I know is simple but still trying to learn.
package tickets;
import java.util.Scanner;
public class tickets {
public static void main(String[] args) {
//program designed to ask how many visitors
//are in a party of people and work out
//the total cost of the entry tickets.
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
//adding code that would give a percentage discount for
//4 adults or more
{
if ( adult1.nextInt() >= 4
{
double adult2 =( adult1.nextInt() * percentage);
}else {
double adult2 = (adult * adult1.nextInt());
System.out.println("please enter the amount of consessions");
Scanner consession1 = new Scanner (System.in);
double consession2 = (consession *consession1.nextInt());
System.out.println("please enter the amount of children");
Scanner child1 = new Scanner (System.in);
double child2 = (child * child1.nextInt());
System.out.println( "total"+" " + (adult2 +consession2 + child2) );
System.out.println("hope you enjoy your visit today!");
//woop woop it works!!!!!!!!!!
}
}
}
}
The reason why your program asked for two inputs was because adult1 is the name of your scanner and in your if statement the condition was if the user input is >= 4 then take an Integer input again from the user and multiply that with percentage and store it in adult2, instead this should be done as follows
public static void main(String[] args)
{
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
double adult2 = 0.0 // you dont need to redeclare below
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
// remove this unneccessary bracket {
int num = adult1.nextInt();
if ( num >= 4)
{
adult2 =( num * percentage);
}
else
{
adult2 = (adult * num);
}
System.out.println("Adult2 is " + adult2);
}
Store the int from the scanner and use that value in your ifs and calculations. You're calling nextInt() more than once and each time you get another int.
After you enter the if or else you will wait for more input of the integer type stopping the program.

copying arrays from a method to main method

I am asked to write a program that requires three arrays in the main method. The program is supposed to calculate gross wages for given employee ids from user input of the pay rate and hours also from user input. Also, it is asking me to write a method calculateWages with three array parameters: hours, payRate, and wages, which calculates and stores the wages for each employee by multiplying the corresponding hours and pay rates.
Your program should display each employee number and ask the user to enter that employee's hours and pay rate. After getting the hours and pay rates for all employees, your program should call calculateWages. Next, your program should display each employee's identification number and gross wages. Note: the number of employees and the minimum wage should both be named constants.
public static void main(String[] args)
{
double[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277,1302850, 7580489}; //Employee IDs of which we are calculating gross wages for
double[] payRate = new double[7];
double[] employeeWages = new double[7];
double[] employeeHours = new double[7];
Scanner keyboard = new Scanner(System.in); //Needed for keyboard input
for (int i = 0; i<employeeID.length; i++)
{
System.out.println("Employee ID: " + employeeID[i]);
System.out.print("Enter the number of hours worked: ");
employeeHours[i]=keyboard.nextDouble();
//Get and validate hours from user.
while(employeeHours[i]<0)
{
System.out.println("Error. Hours worked must not be negative.");
System.out.print("Please enter hours worked: ");
employeeHours[i]=keyboard.nextDouble();
}
//Get and validate pay rate from employees.
System.out.print("Enter the pay rate of employee: ");
payRate[i]=keyboard.nextDouble();
while(payRate[i]<10.24)
{
System.out.println("Error. Minimum pay rate must be at least $10.24");
System.out.print("Please enter the pay rate: ");
payRate[i]=keyboard.nextDouble();
}
}
calculateWages(employeeWages, employeeHours, payRate);
System.out.println("Gross Wages:");
System.out.println();
for(int i=0;i<employeeID.length;i++)
{
System.out.printf("%-9d%-7s",employeeID[i],employeeWages[i]);
}
}
public static String[] calculateWages(double[] employeeWages, double[] inputHours,double[] payRate)
{
String[] formatWage = new String[7];
DecimalFormat formatter = new DecimalFormat("$###.00");
for(int i = 1;i<employeeWages.length;i++)
{
employeeWages[i]=inputHours[i]*payRate[i];
formatWage[i]=formatter.format(employeeWages[i]);
}
return formatWage;
}
}
calculateWages is returning an array so set an array equal to it
String [] result = calculateWages(employeeWages, employeeHours, payRate);

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