Calling methods - java

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.

Related

Need advice with nested if's

I have attempted using a nested if in the following code. I have initialized variables but the compiler is telling me that the variable named 'bill' is not initialized even though it has been. Why is the compiler not recognizing the value assigned to the variable? Please see the notes in the code below.
package killMe;
import java.util.Scanner;
public class Kill_Me {
static Scanner console = new Scanner(System.in);
static double PREMIUM_SERVICE = 55.00;
static double PREMIUM_DAY_OVERTIME_MIN = 0.20;
static double PREMIUM_NIGHT_OVERTIME_MIN = 0.15;
static double REGULAR_SERVICE = 30.00;
static double REGULAR_OVERTIME_MIN = 0.40;
public static void main(String[] args) {
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
} // End of class
No, bill has not been initialized in all cases.
Understand this: the Java compiler will never, ever, evaluate boolean expressions; Simplified version:
double bill;
if (c1) {
bill = v1;
} else if (c2) {
bill = v2;
}
// try and use bill here
Even if, according to your logic, boolean expressions c1 and c2 may cover all possible cases, the compiler cannot ensure that this is the case.
This is the root cause of your error, however deep your if/else, switch, etc statements may be nested.
They were some problems with else statement and variable declarations.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double PREMIUM_SERVICE = 25.00;
double PREMIUM_DAY_OVERTIME_MIN = 0.10;
double PREMIUM_NIGHT_OVERTIME_MIN = 0.05;
double REGULAR_SERVICE = 10.00;
double REGULAR_OVERTIME_MIN = 0.20;
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill = 0.0;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else
{
bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
}
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
}
I'm not sure why it gets this error, but try initialising bill as 0.00 when you declare the variable.
Also,
if(premiumDayMin <0 && premiumNightMin <0)
should probably be changed to
if(premiumDayMin <0 || premiumNightMin <0)
Because you want to make sure that either minutes is not less then zero. You're program should then probably handle this error, because the rest of the program still executes. But maybe you're getting on to that :-P.
I don't recall what I did to stop getting an error message (sorry) but I removed the code if(premiumDayMin <0 && premiumNightMin <0) and replaced it with if(premiumDayMin <= 75 && premiumNightMin <= 100) to stop the code from being redundant. That may have fixed things. I also added another else if to clean the logic up further.

Java - how to charge interest on top of interest

So I'm writing a program for an invoice calculator for class.
However, I need to code interest for every 30 days for 10%
total * interest rate (0.10) if 30 days
So, lets say they need to pay interest for 60 days. so twice
total * interest rate --> with another interest on top of that and so on
another example:
so for the program it depends on the date since last invoice. if it is 30 daysyou will be charged 10% interest. if it is 60 days you will be charged another 10% interest on top of that. if it is 90 days you will be charged another 10% interest on top of that. and so on
Do I use a for loop?
public static void main(String[] args) {
// TODO Auto-generated method stub
DecimalFormat formatter = new DecimalFormat("#0.00");
Scanner input = new Scanner (System.in);
double purchase, invoiceAmount, tax, interest, total = 0;
int validYear, validMonth, validDay, invoiceYear, invoiceMonth, invoiceDay;
int daysdiff;
/* double invoiceAmount = 0;
double tax = 0;
double total = 0;*/
System.out.println("Welcome to the Invoice Calculator\n");
System.out.print("Enter the number of minutes you wish to purchase: ");
purchase = input.nextDouble();
System.out.println("Today's Date");
System.out.print ("Year: ");
validYear = input.nextInt ();
while(validYear < 1950 || validYear > 2016){
System.out.print ("Invalid!!\nEnter Year: " );
validYear = input.nextInt();
}
System.out.print ("Month: ");
validMonth = input.nextInt ();
while(validMonth < 1 || validMonth > 12){
System.out.print ("Invalid!!\nEnter Month: " );
validMonth = input.nextInt();
}
System.out.print ("Day: ");
validDay = input.nextInt ();
while(validDay < 1 || validDay > 30){
System.out.print ("Invalid!!\nEnter day: " );
validDay = input.nextInt();
}
System.out.println("Invoice Date");
System.out.print ("Year: ");
invoiceYear = input.nextInt ();
while(validYear < 1950 || validYear > 2016){
System.out.print ("Invalid!!\nEnter year " );
invoiceYear = input.nextInt();
}
System.out.print ("Month: ");
invoiceMonth = input.nextInt ();
while(invoiceMonth < 1 || invoiceMonth > 12){
System.out.print ("Invalid!!\nEnter month: " );
invoiceMonth = input.nextInt();
}
System.out.print ("Day: ");
invoiceDay = input.nextInt ();
while(invoiceDay < 1 || invoiceDay > 30){
System.out.print ("Invalid!!\nEnter day: " );
invoiceDay = input.nextInt();
}
System.out.println("\nToday's Date is: " + validYear + "/" + validMonth + "/" + validDay);
System.out.println("Invoice Date is: " + invoiceYear + "/" + invoiceMonth + "/" + invoiceDay + "\n");
invoiceAmount = (purchase * 0.02) +5;
tax = (invoiceAmount * 0.13);
total = (invoiceAmount + tax);
interest = (total * 0.10);
// The number of days since invoice date:
daysdiff = (validYear - invoiceYear) *365 + (validMonth - invoiceMonth) *30 +(validDay - invoiceDay);
System.out.print("The number of days since invoice date is: " + daysdiff);
System.out.print("\nInvoice Amount: $");
System.out.println(formatter.format(invoiceAmount));
System.out.print("Tax : $");
System.out.println(formatter.format(tax));
System.out.print("Interest : $");
System.out.println(formatter.format(interest));
System.out.print("TOTAL : $");
System.out.println(formatter.format(total));
}
}
Thank you
if you want to tax 10% for every 30days you'd need something like this.
public class test {
public static void main(String[] args) {
double total = 100.0;
int numDays = 90;
//gets how many times your invoice days goes into 30
int taxNum = numDays / 30;
//decreases total according to your tax
for( int i = 0; i < taxNum; i++ ){
total -= total * .1;
}
System.out.println(total);
}
}

How To Limit User Input In 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.

Getting Java to recognize user input

I'm trying to make a virtual store program. Synopsis is if at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax.
The problem is that the program would ask user for item and quantity once, then it goes into checkout mode. Whenever I put 'q', it goes to the next line.
Here is the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
import java.io.*;
public class virtualStore {
public static void main(String [] args) throws IOException{
/* If the user enters an item number, the program should ask the user to enter how many of that item
they want, and then print the menu again. If at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax. You should use the Math.round() and
System.out.printf methods to round numbers and to display to 2 decimal places. */
Scanner keyboard = new Scanner (System.in);
String input;
char c = ' ';
char q = ' ';
//tax rates
double CAtaxRate = .09;
double NVtaxRate = .07;
double WAtaxRate = .065;
double other = .06;
double tax = 0;
//checkout
double checkout = 0;
double total;
double cash = 0;
double change = 0;
//items
double mushrooms = 0.3;
double onions = 0.6;
double watermelon = 2.5;
double cookies = 1;
int item = 0;
//number of items
int numMushrooms = 0;
int numOnions = 0;
int numWatermelon = 0;
int numCookies = 0;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Alex's Store."
+ " Here is the menu. "
+ "\nEnter the item number to add it to your cart,"
+ " enter \'c\' to checkout or \'q\' to quit. ");
while(true)
//while(c != 'c' && c != 'q')
{
for (item = 1; item < 4; item ++){
System.out.println("Item\t\t\tPrice\t\t\tQuantity");
System.out.println("---------------------------------------------------------");
System.out.println("1. Mushrooms\t\t($0.30/$0.25)\t\t" + numMushrooms);
System.out.println("2. Onions\t\t($0.60/$0.50)\t\t" + numOnions );
System.out.println("3. Watermelon\t\t($2.50/$2.00)\t\t" + numWatermelon);
System.out.println("4. Cookies\t\t($1.00/$0.75)\t\t" + numCookies);
System.out.println("---------------------------------------------------------");
System.out.println("Enter item number between 1 through 4");
System.out.println("or enter 'c' for checkout or 'q' for quit.");
input = keyboard.nextLine();
item = Integer.parseInt(input);
if (input.equals("1"))
{
System.out.println("Enter how many items you want.");
String m = keyboard.nextLine();
numMushrooms = Integer.parseInt(m);
}
else if (input.equals("2"))
{
System.out.println("Enter how many items you want.");
String o = keyboard.nextLine();
numOnions = Integer.parseInt(o);
}
else if (input.equals("3"))
{
System.out.println("Enter how many items you want.");
String w = keyboard.nextLine();
numWatermelon = Integer.parseInt(w);
}
else if(input.equals("4"))
{
System.out.println("Enter how many items you want.");
String co = keyboard.nextLine();
numCookies = Integer.parseInt(co);
}
}
if (numMushrooms > 10)
{
mushrooms = 0.25;
}
else if (numOnions > 10)
{
onions = 0.5;
}
else if (numWatermelon > 10)
{
watermelon = 2;
}
else if (numCookies > 10)
{
cookies = .75;
}
// quit option
String quit = scanner.nextLine();
q = quit.charAt(0);
if (quit.equalsIgnoreCase("q"))
{
System.out.println("Goodbye");
scanner.close();
System.exit(0);
}
// checkout option
String ch = scanner.nextLine();
c = ch.charAt(0);
if (ch.equalsIgnoreCase("c"))
{
//checkout
checkout = numMushrooms * mushrooms + numOnions * onions + numWatermelon * watermelon + numCookies * cookies;
//tax
total = tax * checkout + checkout;
System.out.print("Enter state abbreviations: ");
input = keyboard.nextLine();
PrintWriter outputfile = new PrintWriter("receipt.txt");
outputfile.println("Your cart: ");
outputfile.println("Sub total:$ " + dollar.format(checkout));
if (input.equalsIgnoreCase("CA"))
{
total = CAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + CAtaxRate);
outputfile.println("Tax: $" + dollar.format(CAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("NV"))
{
total = NVtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + NVtaxRate);
outputfile.println("Tax: $" + dollar.format(NVtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("WA"))
{
total = WAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + WAtaxRate);
outputfile.println("Tax: $" + dollar.format(WAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase(input))
{
total = other * checkout + checkout;
outputfile.println("Tax Rate: " + other);
outputfile.println("Tax: $" + dollar.format(other * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
outputfile.println("-----------------------------------------------------");
input = keyboard.nextLine();
cash = Integer.parseInt(input);
outputfile.println("Enter amount of cash: $" + dollar.format(cash));
change = cash - total;
outputfile.println("Change due: $" + dollar.format(change));
outputfile.println("Thank you for shopping at Alex's store!");
outputfile.close();
FileWriter fw = new FileWriter("receipt.text", true);
PrintWriter pw = new PrintWriter(fw);
pw.println("C:\\Desktop\\Receipt.txt ");
pw.close();
}
}
}
}
You're using the wrong model to get user input.
Try doing something that looks like:
while(true) {
// Print the menu messages
String input = scanner.readLine();
if(input.equals("c")) {
// Read in and handle state abbreviation
} else if(input.equals("q")) {
System.exit(0);
} else {
int itemNumber = Integer.parseInt(input);
// Parse and handle item number
}
}

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

Categories

Resources