I am extremely new to java I am in my second week in classes or so--
I need my program to keep going or exit according to the user. It is a payroll calculation and I want the end to say "Do you want to continue (y/n)" I want Y to repeat my entire program of questions and no to end program. I am using Jgrasp and I am very very new. I am assuming it needs a loop and I am not totally sure, I just got this to run and compile correctly-- it runs correctly for me so it is a good start and I am hoping to get help on how to do this as I am seeing a ton of different ways and different programs for it. thanks.
import java.util.Scanner;
public class calculations {
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
double Regpay;
double Payperhour;
int HoursAweek;
double Pay;
double OvertimeHours;
double OvertimePay;
double Dependants;
double SocSecTax;
double FederalTax;
double StateTax;
int UnionDues;
double AllTaxes;
double FinalPay;
String playAgain;
System.out.print("Enter your pay per hour:");
Payperhour = reader.nextDouble ();
System.out.print("Enter your regular Hours a week:");
HoursAweek = reader.nextInt();
System.out.print("Enter your overtime hours:");
OvertimeHours = reader.nextDouble();
Regpay = Payperhour * HoursAweek;
OvertimePay = OvertimeHours * 1.5 * Payperhour;
Pay = OvertimePay + Regpay;
SocSecTax = Pay * .06;
FederalTax = Pay * .14;
StateTax = Pay * .05;
UnionDues = 10;
AllTaxes = SocSecTax + FederalTax + StateTax + UnionDues;
FinalPay = Pay -= AllTaxes;
System.out.println("Your pay this week will be " +FinalPay);
{
System.out.println("How many Dependants:");
Dependants = reader.nextInt();
if (Dependants >= 3) {
Dependants = Pay + 35;
System.out.println("Your Pay is:" +Dependants);
} else if(Dependants < 3) {
System.out.println("Your Pay is:" +Pay);
}
}
}
}
Here is the basic idea with your code:
import java.util.Scanner;
public class calculations{
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
double Regpay;
double Payperhour;
int HoursAweek;
double Pay;
double OvertimeHours;
double OvertimePay;
double Dependants;
double SocSecTax;
double FederalTax;
double StateTax;
int UnionDues;
double AllTaxes;
double FinalPay;
String playAgain;
int runAgain = 1;
while (runAgain == 1) {
System.out.print("Enter your pay per hour:");
Payperhour = reader.nextDouble();
System.out.print("Enter your regular Hours a week:");
HoursAweek = reader.nextInt();
System.out.print("Enter your overtime hours:");
OvertimeHours = reader.nextDouble();
Regpay = Payperhour * HoursAweek;
OvertimePay = OvertimeHours * 1.5 * Payperhour;
Pay = OvertimePay + Regpay;
SocSecTax = Pay * .06;
FederalTax = Pay * .14;
StateTax = Pay * .05;
UnionDues = 10;
AllTaxes = SocSecTax + FederalTax + StateTax + UnionDues;
FinalPay = Pay -= AllTaxes;
System.out.println("Your pay this week will be " + FinalPay);
{
System.out.println("How many Dependants:");
Dependants = reader.nextInt();
if (Dependants >= 3) {
Dependants = Pay + 35;
System.out.println("Your Pay is:" + Dependants);
} else if (Dependants < 3) {
System.out.println("Your Pay is:" + Pay);
}
}
System.out.println("Again??? Press 1 to run again and 0 to exit");
runAgain = reader.nextInt();
}
}
}
Here's a guide for you..
You can create a method for the transaction.
//Place this on your main method
do{
//call the method
transaction();
//ask if the user wants to repeat the program
System.out.print("Do you want to continue (y/n)");
input = reader.nextLine();
}while(input.equalsIgnoreCase("Y"))
public void transaction(){
//your transaction code here..
}
Here is a brief idea of how to do this:
String choice = "y";
while(true) {
//Take input
System.out.print("Do you want to continue (y/n)?");
choice = reader.nextLine();
if(choice.equalsIgnoreCase("n")) break;
//else do your work.
}
You can also sue do-while to get what you want. You may need to make some changes but then that is the entire idea. It is just a hint.
Related
class WageCalculator_1 {
public static void main(String[] args) {
WagecalculatorApp WageCalculatorObject = new WagecalculatorApp();
}
private double baseRate;
private double overtimeMultiplier;
private int hours;
private int overtime;
private int overtimeHours;
private int wages;
private String multi;
Scanner keyboard = new Scanner(System.in);
public WageCalculator_1(double baseRate, int hours)
{
this(baseRate, 1.5, hours);
}
public WageCalculator_1(double baseRate, double overtimeMultiplier, int hours) {
System.out.print("Enter your base rate: ");
baseRate = keyboard.nextDouble();
WageCalculatorObject.wagecalc(baseRate);
System.out.print("Enter your hours: ");
hours = keyboard.nextInt();
WageCalculatorObject.wagecalc(hours);
System.out.print("Would you like to enter an overtime multiplier (yes/no)? ");
multi = keyboard.next();
if (hours > 40) {
System.out.print("what is the overtime multiplier? ");
overtimeMultiplier = keyboard.nextInt();
} else if (hours <= 40) {
wages = (int) (hours * baseRate);
overtimeMultiplier = 0;
} else {
wages = (int) (40 * baseRate);
overtimeHours = hours - 40;
overtime = (int) (overtimeHours * ( 1.5 * baseRate));
wages += overtime;
}
}
}
I have been having issues with WageCalculatorObject. keeps giving me that error when I try to use it. I have been struggling with this quite a bit and don't know what else to do with it. It gives me no error message.
You have no WageCalculatorApp Object. Specifically speaking, unless you give more code, while you initialize the WageCalculatorObject object, you never call it, and therefore any methods you call do not return anything as nothing exists (Unless of course you did not show your code for the WageCalculatorApp). Unless you create a WageCalculatorApp object, nothing can be returned from it as it does not exist.
Im trying to write a code, that computes CD value, for every month.
Suppose you put 10,000 dollars into a CD with an annual percentage yield of 6,15%.
After one month the CD is worth:
10000 + 10000 * 6,15 / 1200 = 10051.25
After the next month :
10051.25 + 10051.25 * 6,15 / 1200 = 10102.76
Now I need to display all the results for the specific number of months entered by the user,
So
month1 =
month2 =
But whth this code I wrote, nothing is printed.
Can you see what's wrong?
Thanks in advance!
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
while (i != months) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
You do not modify neither i nor months in
while (i != months) {
....
}
so if the (i != months) condition is satisfied, the loop runs forever, and you never get to System.out.print statement.
for (int i = 1; i < months; i++) {
while (i != months) {
//you have to modify i or to modify the while condition.
}
if you don't modify i in the while you can't exit from the loop
Corrected code-
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i <= months; i++)
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
}
Note: If you want to print values for each month then the print statement should be inside the loop. You don't need two loops for the objective that you have mentioned above.
As you have been told your code won't get out of the while loop if you don't modify it. Simply remove the while loop. Your code should be like this:
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextDouble();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
}
}
Thanks! Solved it by using
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
instead of while loop.
It works now :) Thanks so much!
each time the program tries to loop, the error "java.lang.stringindexoutofboundsexception" comes up and highlights
ki=choice.charAt(0);
Does anyone know why that happens?. I'm brand new to programming and this has me stumped. Thanks for any help. Any solution to this problem would be amazing.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k = new Scanner(System.in);
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='W' && ki!='B' && ki!='S')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
choice = k.nextLine();
ki= choice.charAt(0);
switch (ki)
{
case 'W':
{
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
}
}while (ki!='X');
The error means there the index "0" is outside the range of the String. This means the user typed in no input, such as the case when you start the program and hit the enter key. To fix this, simply add the following lines of code:
choice = k.nextLine();
if(choice.size() > 0){
//process the result
}
else{
//ignore the result
}
Let me know if this helps!
As you pointed out, the problem is in:
choice = k.nextLine();
ki= choice.charAt(0);
From the docs nextLine(): "Advances this scanner past the current line and returns the input that was skipped."
So in case the user pressed "enter" the scanner will go to the next line and will return an empty String.
In order to avoid it, simply check if choice is not an empty string:
if (!"".equals(choice)) {
// handle ki
ki= choice.charAt(0);
}
Try this:
Your problem was with the Scanner (k) you need to reset it everytime the loop start over.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k;
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='w' && ki!='b' && ki!='s')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
k= new Scanner(System.in);
choice = k.nextLine();
ki= choice.toLowerCase().charAt(0);
switch (ki)
{
case 'w':
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
if(complete.toLowerCase().equals("y"))
break;
}while (ki!='x');
}
}
I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)
I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}