How To Limit User Input In Java - java

The amount of investment must be positive and can be any value.
The period of investment is in years so should be positive.
The annual rate of interest can be between 0.25% to 14%.
import java.util.Scanner;
public class InterestCalculator{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
// Entering the interest rate
System.out.print("Please Enter the annual interest rate between 0.25 to 10 : ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = annualInterestRate / 1200;
System.out.print("Enter number of years: ");
int numberOfYears = input.nextInt();
// Entering the amount earned
System.out.print("Enter Amount: ");
double Amountofinterest = input.nextDouble();
// Calculating
double moneyearned = Amountofinterest * monthlyInterestRate;
// Displaying the results
System.out.println("The money earned is $" +
(int) (moneyearned * 100) / 100.0);
int i;
for (i = 1; i <= numberOfYears * 12; i++) {
double Balance = Amountofinterest + moneyearned;
Amountofinterest = Balance;
monthlyInterestRate = moneyearned + 0.01;
System.out.println(i + "\t\t" + Amountofinterest
+ "\t\t" + monthlyInterestRate + "\t\t" + Balance);
}
}
}
I have made the basic program but, I don't know how to add restrictions.

Are you talking about this :
while(input.nextDouble()<0){
System.out.println("Please enter positive investment");
}

You can use loops that repeatedly ask for input until it's valid:
double annualInterestRate = 0;
while (annualInterestRate < 0.25 || annualInterestRate > 10){
System.out.print("Please Enter the annual interest rate between 0.25 to 10 : ");
annualInterestRate = input.nextDouble();
if (annualInterestRate < 0.25 || annualInterestRate > 10){
System.out.println("Please enter a value between 0.25 and 10");
}
}
//if you reach this point, input is valid because it is neither <0.25 or >10
You can do this for all values that need to meet certain criteria. Just make sure you initialize the variable before the loop and set it as an invalid value, otherwise the loop won't run.
Other variables:
int numberOfYears = -1; //or 0 is you don't allow 0 years
while (numberOfYears < 0){ //or <= 0 if you don't allow 0 years
System.out.print("Enter number of years: ");
numberOfYears = input.nextInt();
}
double Amountofinterest = -1; //or 0
while (Amountofinterest < 0){ //or <= 0
System.out.print("Enter Amount: ");
Amountofinterest = input.nextDouble();
}

Ok you could then use a while loop like this:
int numberOfYears = -1;
System.out.print( "Enter number of years: ");
while(numberOfYears < 0){
numberOfYears = input.nextInt();
}

I'd like to offer a more elegant way of getting data via CLI, where the risk of exception or any other input hazard is minimised.
I've written this function and think it may well cover the Integer, Double and String objects, but you may continue expanding it further:
public Object securedInput(String intro, String type, int maxLength)
{
//Apply Scanner
Scanner input = new Scanner(System.in);
//Show intro
if(intro != null)
System.out.print(intro+" ");
//Get user's input
String inStr = input.next(); //always get a string
//Enforce length
if((maxLength>0)&&(inStr.length() > maxLength))
inStr = inStr.substring(0, maxLength);
String result;
if(inStr == null || inStr.length() < 1)
return null;
switch (type)
{
case "int":
result = inStr.replaceAll("[^0-9]", "");
if(result.length() < 1 || result.length() < inStr.length())
return null;
else
return Integer.parseInt(result);
case "double":
result = inStr.replaceAll("[^0-9.]", "");
if(result.length() < 1 || result.length() < inStr.length())
return null;
else
return Double.parseDouble(result);
//break;
case "string":
result = inStr.replaceAll("[^a-zA-Z .-]", "");
if(result.length() < 1 || result.length() < inStr.length())
return null;
else
return result;
default:
return null;
}
}
Here,as you can see I first take the input as String, then clean it according to my need, and then try to convert it without the risk of getting any exception.
And if something is wrong you simply get a null.
This can be used like this:
Integer i = (Integer)securedInput("Enter an integer:","int", 3);
Double d = (Double)securedInput("Enter a double","double",4);
String s = (String)securedInput("Enter a string","string",2);
You can add further arguments, such as range, and forbidden characters and even output errors according to the problem.
Hope this had helped.

Related

Ignoring of negative values from Java Arraylist for calculations

The idea of my code is that it asks user the income of each month, until the user imputs negative value, which should not be added to the total income and which should be shown in output, but ignored in calculations.
Then the code calculates the total income (ignoring the last negative value), the average income (ignoring the negative value) and the biggest/maximum value of all values. I don't have problems getting right that maximum value. But how could I ignore the negative income in calculations, and maby even not to add it at all to the array?
The problem is that the calculation adds also the negative value/income to the total sum and average income calculations. And it does not ignore the month of the negative income.
Here is my code so far:
package income;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Income {
public static void main(String[] args) {
int sum = 0;
int months = 0;
Scanner input = new Scanner(System.in);
System.out.println("Write the income of each month.");
ArrayList<Integer> array = new ArrayList<Integer>();
System.out.println("Write the income of month 1: ");
int income = input.nextInt();
sum += income;
months++;
array.add(income);
while(true){
months++;
System.out.println("Write " + months + ". month income: ");
if(income >= 0){
income = input.nextInt();
sum += income;
array.add(income);
}
else if (income < 0){
break;
}
}
/*This did not work
for(int i= 0; i < array.size(); i++){
if(income < 0){
array.remove(i);
}
}*/
months--;
System.out.println("The total income is " + sum);
System.out.println("The average income is " + sum/months);
//This one below works fine
System.out.println("The biggest income is " + Collections.max(array));
}
}
Although you are indeed adding the last negative number into account in the calculations, this is not the ultimate reason why your code is not working. You are actually checking whether the previous input you read is greater than 0 here:
while(true){
months++;
System.out.println("Write " + months + ". month income: ");
if(income >= 0){ <------
income = input.nextInt();
So the loop will only stop if the previous input is less than 0. In other words, when you enter e.g. -1 in, the input is not checked until the next iteration of the loop, at which point -1 has already been added to the array. Therefore, you should instead check income >= 0 immediately after nextInt:
System.out.println("Write the income of each month.");
ArrayList<Integer> array = new ArrayList<>();
while(true){
months++;
System.out.println("Write the income for month" + months + ":");
int income = input.nextInt();
if(income >= 0){
sum += income;
array.add(income);
}
else {
break;
}
}
Note that I've also removed the bit between Write the income of each month. and the while loop, as it is redundant.
I suppose this is what you are looking for.
var list = new ArrayList<Integer>();
var in = new Scanner(System.in);
var i = 0;
System.out.println("Write Income of Each Month.");
while (true)
{
System.out.print("Write " + ++i + ".month income : " );
int num = in.nextInt();
if (num < 0)
{
int sum = list.stream().mapToInt(Integer::intValue).sum();
double avg = (double) sum / --i;
int max = Collections.max(list);
System.out.printf("Sum : %d\nAverage : %f\nBiggest Number : %d\nNegative No. %d", sum ,avg, max, num);
break;
}
else
{
list.add(num);
}
}
You could use the Integer.signum(int) function to know whether the value is negative (returned value = -1) or zero (returned value = 0) or positive (returned value = 1). So, basically ignore if Integer.signum(income) == -1

Java -vending machine that can't accept pennies

So I'm working on a java project that involves creating a soda machine that adjusts price based on temperature. I can't seem to figure out how to make sure the machine does NOT accept pennies when accepting payment from the user.
I feel like I'm overcoding but I'm at my wit's end because I don't have any clue how to not accept pennies.
import java.util.*;
import java.text.*;
public class SodaMachine extends SodaTester
{
public static void main(String[] args)
{
double temp;
double money;
double change;
double price1 = .50;
double price2 = .55;
double price3 = .60;
double price4 = .65;
double price5 = .75;
double price6 = .80;
double price7 = .85;
double price8 = .90;
double price9 = 1.00;
System.out.println("Hi there! Please enter the temperature in Farenheit:");
Scanner scan = new Scanner(System.in);
temp = scan.nextDouble();
DecimalFormat fmt = new DecimalFormat("0.#");
NumberFormat fmt2 = NumberFormat.getCurrencyInstance();
if (temp < 40 || temp > 120)
{
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
while (temp < 40 || temp > 120)
{
temp = scan.nextDouble();
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
}
}
if(temp < 50 && temp >= 40)
{
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price1));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price1)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price1));
money = scan.nextDouble();
}
change = money - price1;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp >= 50 && temp <= 60) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price2));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price2)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price2));
money = scan.nextDouble();
}
change = money - price2;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 60 && temp <= 65) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price3));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price3)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price3));
money = scan.nextDouble();
}
change = money - price3;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 65 && temp <= 70) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price4));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price4)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price4));
money = scan.nextDouble();
}
change = money - price4;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 70 && temp <= 75) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price5));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price5)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price5));
money = scan.nextDouble();
}
change = money - price5;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 75 && temp <= 80) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price6));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price6)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price6));
money = scan.nextDouble();
}
change = money - price6;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 80 && temp <= 85) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price7));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price7)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price7));
money = scan.nextDouble();
}
change = money - price7;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 85 && temp <= 90) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price8));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price8)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price8));
money = scan.nextDouble();
}
change = money - price8;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 90 && temp <= 120) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price9));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price9)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price9));
money = scan.nextDouble();
}
change = money - price9;
System.out.println("Your Change is: " + fmt2.format(change));
}
}
}
I won't go into detail about your current code, but you basically want to check if the decimal value you've read from the user modulo-0.05 equals 0 (so it has no remainder). One issue in this is that floating point precision can interfere with the checks when you use double, which is why you'd always want to use java.math.BigDecimal for currency calculations.
Here an example:
BigDecimal input = new BigDecimal(scanner.next());
if(input.remainder(new BigDecimal("0.05")).compareTo(BigDecimal.ZERO) == 0){
System.out.println("Input "+input+" is valid!");
} else{
System.out.println("Input "+input+" is not valid!");
}
For the inputs "1", "1.00", "1.05", "4.35", "1.01", "3.21", "4.68" it will output the following:
Input 1 is valid!
Input 1.00 is valid!
Input 1.05 is valid!
Input 4.35 is valid!
Input 1.01 is not valid!
Input 3.21 is not valid!
Input 4.68 is not valid!
Try it online.
Since BigDecimal can be quite confusing for new Java users, you could perhaps let the user input the amount in cents (so as integers), in which case it can be something like this instead:
int input = scanner.nextInt();
if(input % 5 == 0){
System.out.println("Input "+input+" is valid!");
} else{
System.out.println("Input "+input+" is not valid!");
}
For the input "100", "105", "435", "101", "321", "468" it will output the following:
Input 100 is valid!
Input 105 is valid!
Input 435 is valid!
Input 101 is not valid!
Input 321 is not valid!
Input 468 is not valid!
Try it online.
EDIT: Since I had some time, I reworked your solution with re-usable methods.
Please have a good look what I did, and if you have any questions about specific parts let me know. It now uses recursive methods until the user enters a valid input. The boolean showMessage parameters in the methods are to show the "Please enter X" messages only once.
import java.lang.IllegalArgumentException;
import java.lang.NumberFormatException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SodaMachine{
private static final String currencySymbol = "$";
private static final BigDecimal roundOn = new BigDecimal("0.05");
private Scanner scanner;
private NumberFormat currencyFormat;
public SodaMachine(){
scanner = new Scanner(System.in);
currencyFormat = NumberFormat.getCurrencyInstance();
}
public static void main(String[] args){
SodaMachine sodaMachine = new SodaMachine();
double farenheitInput = sodaMachine.enterFarenheit(true);
System.out.println("The temperature in degrees Farenheit you've entered is: " + farenheitInput);
BigDecimal price = sodaMachine.determinePrice(farenheitInput);
System.out.println("The price is: " + sodaMachine.currencyFormat.format(price));
BigDecimal payment = sodaMachine.enterPayment(price, true);
BigDecimal change = payment.subtract(price);
System.out.println("Your change is: " + sodaMachine.currencyFormat.format(change));
}
private double enterFarenheit(boolean showMessage){
if(showMessage){
System.out.println("Hi there! Please enter the temperature in Farenheit:");
}
double farenheitInput;
try{
farenheitInput = scanner.nextDouble();
} catch(InputMismatchException ex){
scanner.nextLine(); // Get rid of the invalid user-input
System.out.println("The value you've entered is not a valid. The input should be a decimal input. Please try again.");
return enterFarenheit(false);
}
if(farenheitInput < 40 | farenheitInput > 120){
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
return enterFarenheit(false);
}
return farenheitInput;
}
private BigDecimal determinePrice(double farenheit){
String strPrice;
// Temperature is in the range [40, 50):
if(farenheit >= 40 && farenheit < 50){
strPrice = "0.50";
}
// Temperature is in the range [50, 60]:
else if(farenheit >= 50 && farenheit <=60){
strPrice = "0.55";
}
// Temperature is in the range (60, 65]:
else if(farenheit > 60 && farenheit <= 65){
strPrice = "0.60";
}
// Temperature is in the range (65, 70]:
else if(farenheit > 65 && farenheit <= 70){
strPrice = "0.65";
}
// Temperature is in the range (70, 75]:
else if(farenheit > 70 && farenheit <= 75){
strPrice = "0.75";
}
// Temperature is in the range (75, 80]:
else if(farenheit > 75 && farenheit <= 80){
strPrice = "0.80";
}
// Temperature is in the range (80, 85]:
else if(farenheit > 80 && farenheit <= 85){
strPrice = "0.85";
}
// Temperature is in the range (85, 90]:
else if(farenheit > 85 && farenheit <= 90){
strPrice = "0.90";
}
// Temperature is in the range (90, 120]:
else if(farenheit > 90 && farenheit <= 120){
strPrice = "1.00";
}
// Invalid temperature range:
else{
// Since we already validated the input-range, it should never go here,
// but added it just in case.
throw new IllegalArgumentException("The temperature must be in the range [40, 120]!");
}
return new BigDecimal(strPrice);
}
private BigDecimal enterPayment(BigDecimal price, boolean showMessage){
if(showMessage){
System.out.println("Please enter amount of payment: ");
}
String userInput = scanner.next();
// Remove the optional currency symbol from the user input
userInput = userInput.replace(currencySymbol, "");
BigDecimal paymentInput;
try{
paymentInput = new BigDecimal(userInput);
} catch(NumberFormatException ex){
scanner.nextLine(); // Get rid of the invalid user-input
System.out.println("The value you've entered is not a valid. The input should be a price input. Please try again.");
return enterPayment(price, false);
}
if(paymentInput.compareTo(price) < 0){
System.out.println("Your payment of " + currencyFormat.format(paymentInput) + " is too low. Please try again. The total price is: " + currencyFormat.format(price));
return enterPayment(price, false);
}
if(paymentInput.remainder(roundOn).compareTo(BigDecimal.ZERO) != 0){
System.out.println("Your payment should be rounded to " + currencyFormat.format(roundOn) + ". Please try again.");
return enterPayment(price, false);
}
return paymentInput;
}
}
Try it online.
Your code can be simplified alot, but I will focus on the issue at hand.
I would create a function to get user input, ensuring it does not contain pennies:
double getMoney(String prompt, Scanner scan)
{
double money = 0;
while(true) { // Loop until proper input
System.out.println(prompt);
money = scan.nextDouble();
// There are a few ways to determine if it has pennies.
// I will convert to int and check if it is divisible
// by 10 or 5
int i = (int)Math.round(money * 100); // Convert to pennies
if (0 == i % 5) {
// It's ok, return
return money;
}
}
}
Side note: using floating point for currency is bad practice. Floating point can introduce rounding errors. It's better to use integers and store the values using the lowest denomination. In this case pennies.

Checking for negative numbers in Array and re-prompting for correct input

The idea is to create an average for money made in a week by day and my average must be calculated in a method that is called in the main method. That is the easy part, but the part I'm stuck on is if a number less than zero is entered it should give me an error message and re-prompt the user for a better value. I'm not looking for a handout here just for someone to tell me what I've been doing wrong if it is simple and easy or a pointer in the right direction.
import java.util.*;
public class weeklyAveragesClient2
{
public static void main(String [] args)//output averages in format
{
averageCash();
}
public static double averageCash()//use array and loop to calculate weekly average
{
double [] cashMoney;
cashMoney = new double[7];
Scanner scan = new Scanner(System.in);
int j = 0;
String s = "ERROR";
while (j < 7)
{
double num = cashMoney[j];
if (num == 0)
{
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
}
else if(num > 0)
{
System.out.print("Please enter an amount for day " + (j+1) +": ");
cashMoney[j] = scan.nextDouble();
j++;
}
else
{
System.out.println("Error: negative number please enter a number > 0");
}
}
System.out.println("Calculating...");
double sum = 0;
for (int i = 0; i < cashMoney.length; i++)
{
sum = sum + cashMoney[i];
}
double average = sum / (double)cashMoney.length;
System.out.println("Average: " + average);
return average;
}//end averageCash
}//end class
I've added some comments that will hopefully provide food for thought.
// This will *always* be zero at first because you haven't called scan.nextDouble() yet
// and zero is the default value. So when you run the program, it will output "Error
// please enter a number > 0" before doing anything else
if (num == 0) {
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
} else if (num > 0) {
System.out.print("Please enter an amount for day " + (j + 1) + ": ");
cashMoney[j] = scan.nextDouble();
j++;
} else {
// If we get into this state, the user will never be invited to enter
// another number, since the last entered number was negative, so
// num == 0 is false, and
// num > 0 is false, so
// we'll end up back here. In fact, you'll enter an infinite loop and
// this message will be printed over and over again.
System.out.println("Error: negative number please enter a number > 0");
// cashMoney[j] = scan.nextDouble(); // <-- try prompting the user again
}
Please also consider indenting your code correctly. It will greatly increase readability. If you're using an IDE like Eclipse, you can select Source > Format.

My sentinel controlled while loop is not working

I can't get the while loop to work. The Program prompt user whether (s)he wants to continue, enter 0 toquit or any other integer to continue. If the user wants to c
ontinue, the program will loop back to themenu, otherwise, it will exit. Thus, you should have a sentinel-controlled loop that will end when a 0 is entered
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
while(gender != 0);//begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if(gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if(gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if(gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
}
}
}
This line is responsible:
while(gender != 0);//begin sentinel controlled while loop
Look closely. There is a semi-colon at the end - that is the entire statement. The {} block that follows does not belong to the loop (and is executed exactly once).
Try dropping the ; from the end - we've fixed our while loop, but now the {} loop body doesn't execute at all. This is because gender is initialized with a value of 0. So to get our loop to execute at least once we need to either initialize gender to something else, or use a do-while loop.
Here is the modified code using a do-while.
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
do //begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if (gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if (gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if (gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
} while(gender != 0); //end sentinel controlled while loop
}
}
Try this:
while(gender != 0);//<-- remove the semi colon,loop gets terminated by it
Also declare gender as:
int gender = -1;//<-- this will cause the loop to start

Calling methods

I have a project in mind however there are a few basics I need to master before I can proceed. Here's the issue I'm trying to call a function from main in java but I can't get it to compile. I have read the feedback and I went with using a switch to call each function. I always get "error can't find symbol". I've made a few changes here and there trying to get it to run. Once again I feel like I'm lacking something very fundamental and it's preventing me from getting this to work. Any ideas
import java.util.*;
import java.lang.*;
import java.io.*;
class Practice {
static void wagecalc() {
Scanner input = new Scanner(System.in);
System.out.println("Input pay per hour:");
int a = input.nextInt();
int b;
System.out.println("Input hours worked:");
b = input.nextInt();
int c;
System.out.println("Input days worked:");
c = input.nextInt();
int gross = a * b * c;
System.out.println("Your gross pay is:" + gross);
// Determining tax rate//
if (gross < 10000) {
int taxrate = gross * 10 / 100;
System.out.println("Your tax rate is 10%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 10000 || gross <= 30000) {
int taxrate = gross * 15 / 100;
System.out.println("Your tax rate is 15%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross >= 30000 || gross <= 70000) {
int taxrate = gross * 20 / 100;
System.out.println("Your tax rate is 20%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 70000) {
int taxrate = gross * 25 / 100;
System.out.println("Your tax rate is 25%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
}
static void autocalc() {
Scanner input = new Scanner(System.in);
// Declaring the variables as an integer//
int auto;
int loan;
int interest;
int mnydwn;
int pymnt;
int year;
int month = 12;
int tap;
int term = year * month;
int spec;
System.out.println("Please enter the following information for your car loan:/n");
System.out.println("Please enter the amount of the vehicle you wish to purchase:/n");
auto = input.nextInt();
System.out.println("Please enter the amount of money you wish to put down:/n");
mnydwn = input.nextInt();
System.out.println("Please enter the interest rate:/n");
interest = input.nextInt();
System.out.println("Please enter the term of the loan (years):/n");
year = input.nextInt();
System.out.println("Processing......../n");
System.out.println("Processing............");
// Calculations//
loan = auto - mnydwn;
int intamt = loan * interest;
tap = loan + intamt;
pymnt = tap / term;
// Display//
System.out.println("Process...Complete./n");
System.out.println("Car amount:" + auto);
System.out.println("Loan recieved:" + loan);
System.out.println("Interest rate:" + interest);
// if statement for proper output of year//
if (year == 1) {
System.out.println("Your monthly payments will be" + pymnt + "for a" + year + "year" + term + "months.");
} else if (year > 1) {
System.out.println("Your monthly payments will be" + pymnt + "for" + year + "years" + term + "months.");
}
System.out.println("Total amount paid at the end of the term" + tap);
}
public static void main(String[] args) throws java.lang.Exception {
// User input//
Scanner input = new Scanner(System.in);
int count = 0; // Count for the while loop//
// Instructions on how to begin interface//
System.out.println("Hi!/n");
System.out.println("...Thanks for using D Anomaly's Finance calculator!!/n");
System.out.println("Please choose one of the following:/n");
System.out.println(" 1. Wages:/n");
System.out.println(" 2. Auto Loan:/n");
// System.out.println(" 3. Home Loan:/n");//
System.out.println("Choose 1-3");
int calc = input.nextInt();
switch (calc) {
case 1:
wagecalc();
break;
case 2:
autolcalc();
break;
case 3: // homecalc();//
break;
if (calc >= 4) {
System.out.println(" Invalid entry!!!/n");
System.out.println("Please try again:");
break;
}
}
}
}
There are a few problems here, including the following:
1.
public void wageinformation(int gross) needs to be declared static if you want to call it from main()
2.
You are calculating int gross = a * b * c right after you have received it as a parameter.
3.
You have (or had in the initial version of this post) several extra braces.
4.
The deduction and total variables are never declared within the wageinformation() method.
I would strongly suggest working through some online Java tutorials if you are looking to improve your skills.

Categories

Resources