I have just started learning Java in a college course. If/then statements haven't been covered yet but I figured I could try them on my own. I ended up with some syntax errors which I think I fixed, but now it seems like there are operand errors when I try adding a string with integers.
The problem given in my class was to ask the user for their name, hourly rate of pay, and how many hours they worked. I know the professor will soon ask us to ask the user if they get paid overtime. If they do, ask after how many hours overtime is paid. And then calculate the total payment, with any overtime pay being 1.5x of the regular hourly rate.
However I get an error in the last 3 print statements, which I assume is because I am trying to combine a string and an integer. How do I fix this?
package javaapplication2;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String name;
double payRate;
int hours;
Boolean OTyn;
int OTy;
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("What is your hourly rate of pay?");
payRate = input.nextDouble();
System.out.println("How any hours have you worked?");
hours = input.nextInt();
System.out.println("Your boss pays overtime. Answer with true or false.");
OTyn = input.nextBoolean();
if (OTyn == true)
System.out.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy)
System.out.println("Your weekly pay is " + ((40 * payRate) + (hours - OTy)(payRate * 1.5)));
else
System.out.println("Your weekly pay is " + payRate * hours);
else
System.out.println("Your weekly pay is " + payRate * hours);
}
}
I think you are missing the {} on the ifs
if (OTyn == true) { //here
System.out.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy){ // Here doesn need because it is just one line after the if
System.out.println("Your weekly pay is " +
((40*payRate) + (hours - OTy)(payRate*1.5)));
// (hours - OTy)(payRate*1.5) you are missing an operator between this expressions
}else{
System.out.println("Your weekly pay is " + payRate*hours);
}
} else { //here
System.out.println("Your weekly pay is " + payRate*hours);
} //and here
Plus for an IF statement that has just one line after it you doesn't need the {} as this:
if ( something )
System.out.println("Something is true");
else
System.out.println("Something is false");
You were missing one set of braces and an asterisk as follows.
if (OTyn == true) { // <-- This brace to open.
System.out
.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy)
System.out.println("Your weekly pay is "
+ ((40 * payRate) + (hours - OTy)
* (payRate * 1.5))); // <-- at the start of this line.
else
System.out.println("Your weekly pay is "
+ payRate * hours);
} else // <-- That brace to close.
System.out.println("Your weekly pay is "
+ payRate * hours);
import java.util.Scanner;
public class JavaApplication2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
double payRate;
int hours;
Boolean OTyn;
int OTy;
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("What is your hourly rate of pay?");
payRate = input.nextDouble();
System.out.println("How any hours have you worked?");
hours = input.nextInt();
System.out.println("Your boss pays overtime. Answer with true or false.");
OTyn = input.nextBoolean();
if (OTyn == true){
System.out.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy){
System.out.println("Your weekly pay is " + ((40*payRate) + (hours - OTy)*(payRate*1.5)));
}
else{
System.out.println("Your weekly pay is " + payRate*hours);
}
}
else {
System.out.println("Your weekly pay is " + payRate*hours);
}
}
}
Try this, not only were you missing braces, you also had a problem with this line
System.out.println("Your weekly pay is " + ((40*payRate) + (hours - OTy)(payRate*1.5)));
you need a * between (hours - OTy) and (payRate*1.5)to result in (hours - OTy)*(payRate*1.5) otherwise the string concatenation will not work
Related
this project i use do while loop with switch case to check the input case is not match or not. i run the code but the result not what i wanted. what i expect is if the user type the wrong case, the do while loop will loop back to the input where user need to enter the case.
here is the code
package vending.machine;
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
import static vending.machine.adddrinks.drinksList;
public class VendingMachine {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
double money;
double total;
double balance;
do{
System.out.println("\nPlease insert money:");
money = sc.nextDouble();
if(money < 1.2){
System.out.println("Not enough money");
}
}while(money < 1.2);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
System.out.print("Select: 1 or 2 or 3 or 4\n");
int select=sc.nextInt();
do{
switch(select){
case 1:{
total = adddrinks.drinksList.get(0).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 2:{
total = adddrinks.drinksList.get(1).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 3:{
total = adddrinks.drinksList.get(2).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 4:{
total = adddrinks.drinksList.get(3).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
default:{
System.out.println("Invalid");
break;
}
}
}while(select<5);
}
}
here is the result
enter image description here
From what I understood from your code. When you are giving the input as 5 it is giving invalid.
After that it will go to the while statement and check the condition there. If you are inside the switch case and select any random case It will show you invalid. After that depending upon the number that you have entered.
If the number is less than 5, It will again go to switch case.
As it doesn't make sense as If you continue to provide correct input to it. The code will continue to execute making the balance going in the negative. this condition should be changed to
while(balance>1.2)
assuming that it is minimum amount that is necessary to buy a drink. This will check the condition after every drink and will hopefully do what you were hoping.
On side Note : Make your code modular.
You need to loop over your input, i was so free to improve your code a bit (sorry I do not like repetations):
private static void main10(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
int select = 0;
double balance = 0;
boolean running = true;
while (running) {
if (sc.hasNextInt()) {
select = sc.nextInt();
if (0 < select && select <= adddrinks.drinksList.size()) {
double price = adddrinks.drinksList.get(select - 1).getdrinkPrice();
if (balance < price) {
System.out.println("Not enough money, " + select + " costs " + price);
} else {
balance -= price;
System.out.println("You choosed " + select + " , you will find it in the dispenser");
}
} else {
System.out.println("Invalid input, please retry");
}
} else if (sc.hasNextDouble()) {
balance += sc.nextDouble();
} else {
String input = sc.next();
if (input == "q") {
running = false;
if (0 < balance)
System.out.println("please don't forget your change with amount of: " + balance);
System.out.println("Have a nice day, happy to see you again");
break;
} else if (input == "h") {
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
} else {
System.out.println("Invalid input, please retry");
}
}
System.out.println("Your balance is: " + balance);
System.out.println(
"please chouce your product (e.g 2), enter coins (e.g 2.0), click on 'h' to show product list or click on 'q' to get your change");
}
}
I've written a program that "buys" and "sells" bitcoin, although my buy function is giving incorrect math results.
In my program, I have $20000 (double USD) and bitcoin (which is worth $4000.
All its supposed to do is deduct how many bitcoin you are buying from your USD.
Every time I use the buy function (input 1) to buy at least 2 at a time, it works once, and then calculates incorrectly. It goes from 20000 to 12000 (correctly) and then from 12000, to -4000. I can't figure out what's wrong with my code. I know the answer is probably simple, but I feel like I've tried everything.
import java.util.*;
public class P3a {
public static void main(String[] args) {
Dates d = new Dates();
String s = d.getDate();
System.out.println("Date is" + s);
W3 mywallet = new W3();
Scanner myscanner = new Scanner(System.in);
double buy = 0.0;
int choice = 0;
double bitcoin = 4000;
double USD = 20000;
while (choice != 5) {
System.out.println("Welcome! Enter a command. \n"
+ "Enter 1) Buy Bitcoin \n"
+ "Enter 2) Sell Bitcoin \n"
+ "Enter 3) Print Balance \n"
+ "Enter 4) Print History \n"
+ "ENTER 5) Exit Program\n");
choice = myscanner.nextInt();
if (choice == 1) {
System.out.println("How many? ");
buy = myscanner.nextDouble();
mywallet.add(buy);
bitcoin = bitcoin * buy;
USD = USD - bitcoin;
System.out.println("you have bought:" + mywallet.numcoins);
System.out.println(USD);
} else if (choice == 2 && USD >= bitcoin) {
System.out.println("How many?");
buy = myscanner.nextDouble();
mywallet.subtract(buy);
System.out.println("you have sold:" + mywallet.numcoins);
USD = USD + bitcoin;
System.out.println(USD);
} else if (choice == 3) {
System.out.println("Balance:" + mywallet.numcoins);
} else if (choice == 4) {
System.out.println("Print Transaction history");
} else if (choice == 5) {
// exit
break;
}
}
System.out.println("Bye");
}
}
You are not resetting the bitcoin variable.
On the first iteration you run:
bitcoin = bitcoin * buy;
This will set bitcoin to be equal to 4000 * 2.
On the second iteration you run the same line. This will then set bitcoin to be equal to (4000 * 2) * 2.
You need to reset the value of bitcoin to 4000 once you are done using it.
You can either reset the value of bitcoin at the end of the if statement:
if (choice == 1) {
System.out.println("How many? ");
buy = myscanner.nextDouble();
mywallet.add(buy);
bitcoin = bitcoin * buy;
USD = USD - bitcoin;
System.out.println("you have bought:" + mywallet.numcoins);
System.out.println(USD);
bitcoin = 4000; // this line was added
} else if (choice == 2 && USD >= bitcoin) {
Or even better:
Create a final static variable representing the price of the bitcoin, then utilize that in calculations needing that price constant. It would look something like this:
public class P3a {
private static final double BITCOIN_VALUE = 4000;
...
// your other code
...
buy = myscanner.nextDouble();
mywallet.add(buy);
bitcoin = BITCOIN_VALUE * buy;
USD = USD - bitcoin;
System.out.println("you have bought:" + mywallet.numcoins);
...
bitcoin = bitcoin * buy;
USD = USD - bitcoin;
You're changing the state of the program here. After the first run, USD is 12000, but bitcoin becomes 8000. So next time you do the same thing you get the unexpected value.
Use temporary variables inside the while-loop so that the original variables are not overwritten. In fact, it'd be better to mark bitcoin as a final variable.
This is my first post here, so forgive me for any formatting errors.
So as you can see my program requests the gender, # of accidents and year of car to display a fictitious insurance quote.
Based on all that information I need to add the subtotal of the insurance cost to the end.
I have my code working up until the Total Cost comment (posted it all for reference). I am stuck there because the genders have different base amounts. I'm trying to figure out a way to only do one if statement if it matches the gender that was input by the user.
Any ideas?
import java.util.*;
public class Insurance {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int currentYear = 2017; //used for calculating the age of the users car
int maleGender = 1000;
int femaleGender = 500;
//Letting user know they are inputting data for car insurance purposes
System.out.println("Car insurance questionnaire. Please input correct information when prompted.");
// gender information from user
System.out.println("What is your gender? m/f");
String gender = scanner.next();
// accident quantity information from user
System.out.println("How many accidents have you had?");
int acc = scanner.nextInt();
// car year information from user
System.out.println("What year was your car manufactured?");
int carAge = scanner.nextInt();
//if statements which refer to the users data input
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
} else {
System.out.println("You are a female.\nThe base cost is $500.");
}
if (acc == 0) {
System.out.println("You have no accidents. Insurance increase is $0.");
} else if (acc >= 1) {
System.out.println("You have " + acc + " accidents. Insurance increase is $" + acc * 100 + ".");
}
if (carAge >= 2007) {
System.out.println("Your car is " + (currentYear - carAge) + " years old.\nYour car is still in warranty, no savings added.");
} else
System.out.println("Your car is out of warranty, final cost is halved.");
//Total cost
/*
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + femaleGender) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + femaleGender) + ".");
*/
}
}
I am not totally sure how you want to calculate your result but if do NOT want to use femaleGender all the time but in dependency of the gender different values then maybe something like this could help:
int baseAmount = gender.equals("m") ? maleGender : femaleGender;
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + baseAmount ) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + baseAmount ) + ".");
}
int genderCost;
...
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
genderCost = maleGender;
} else {
System.out.println("You are a female.\nThe base cost is $500.");
genderCost = femaleGender;
}
...
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + genderCost) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + genderCost) + ".");
}
Put the amount for gender in a variable genderCost when the gender input variable is evaluated and use genderCost when you calculate the total.
I am trying to prompt the user if the information they entered is correct and the program just proceeds anyway instead of re-prompting the user. I think i need to change how I loop this do some type of do-while loop, but I don't quite know what to do.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
if (quarterNumber > 10 || quarterNumber < 0)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
I probably figured what your problem is.
Example code snippet: (Note I am doing without an actual java editor so just handle any missing syntax
//Here we will prompt the user to enter the amount of quarters
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
The idea is for a recursive prompt. The application first prompts the user to type in the result, and then you handle the amount of So you have to handle the prompt within the do-while loop. Assuming you don't want to repeat the same old text, you can do what I did (which is much cleaner in my opinion).
EDIT: Assuming you want to handle the entire repeating of the application. place everything for the declaration of variables into a method (or better various methods for cleaner handling, and handle something like this.
int quarters;
double balance;
//TODO : Add all other required variables
string verification;
do
{
quarters = getNumberOfQuartersFromUser();
balance = getStartingBalance();
... //TODO : all the other methods
//verification
System.out.println("Is this accepted?");
verification = keyboard.nextString();
//Handle verfication if it is no or No
if (verification == null || verification == "No" || verification == "no")
{
System.out.println("Starting from the beginning again");
}
}
while (verification == null || verification == "No" || verification == "no")
//out of loop, so handle calculation.
...
and a method snippet
private int getNumberOfQuartersFromUser()
{
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
return quarters;
}
I think you should enclose your codes to Else statement to avoid proceeding unintentionally. Remember that else limits the run-time of your codes and put it on a more specified path for you.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
//Here you had started your condition I'll try to make it nested if statement
if (quarterNumber > 10 || quarterNumber < 0)
//if the condition is true perform this
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
else{
//if false conditions inside else statement should be performed
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
//you could put another if statement inside if statement which is known as nested if statement.
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
else{
//like before you should enclose this to else to avoid confusion
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
}
Remember that learning nested if statement is essential to a programmer. without this, all your conditions will literally proceed.
import java.util.Scanner;
public class Teacher{
public static void main(String [] args){
Scanner reader = new Scanner(System.in);
double salary;
double pi;
int year;
int years = 1;
double predict;
double predict2 = 0;
double sum = 0;
System.out.print("What is your starting salary: ");
salary = reader.nextDouble();
System.out.print("What is your precentage increase: ");
pi = reader.nextDouble();
System.out.print("How many years are you working: ");
year = reader.nextInt();
if (salary <= 0){
System.out.print("The salary must be positive.");
}
if (pi <= 0){
System.out.print("The percentage increase must be positive.");
}
if (year < 0){
System.out.print("The years must be positive.");
}
while (year > years) {
predict = salary * (pi/100);
System.out.println(years + ". " + predict);
years++;
if (years == year){
break;
}
}
}
}
I am having trouble trying to print out a loop. Every time I run the program, this segment only prints out one number and doesn't print out the rest.
per #ajb wouldn't you want to do something like this in your loop? This will print your salary increase every year, and also add that to the salary for the next iteration
Per your new comment
Every time their is an output, I would like it to display the year and
their salary.
while (year > years) {
//predict = salary * (pi/100); commented this because it is not necessary anymore.
salary += salary * (pi/100);
System.out.println(years + ". " + salary); // replaced predict with salary, to show their salary and not just their predicted raise.
years++;
// This block of code will never be hit, therefore it is not needed.
//if (years == year){
// break;
//}
}
Revised could be something like this.
while (year > years) {
salary += salary * (pi/100);
System.out.println(years + ". " + salary);
years++;
}