i am new to programming, and i was wondering if i could get some help. My program stops running at System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");. I am open to any suggestion. Also, please point out anything else wrong with this program. Thanks!
import java.util.Scanner;
public class Interest
{
double userInput;
double interest;
double time;
double amount;
double answer;
Scanner myScanner = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
}
{
System.out.println("Please enter your percent of interest in a decimal format: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
interest = userInput;
}
else
{
System.out.println("Please enter a integer for your percent of interest.");
}
}
{
System.out.println("Please enter the time the interest is applied for: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
time = userInput;
}
else
{
System.out.println("Please enter an integer for the time the interest is applied for.");
}
}
{
System.out.println("Please enter your amount of money that the interest is applied to: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
amount = userInput;
}
else
{
System.out.println("Please enter an integer for the amount of money that the interest is applied to.");
}
}
{
answer = (amount * interest * time);
}
{
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
}
}
Get rid of all the extra braces; they're outside your main method.
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
// } <-- remove
// { <-- remove
System.out.println("Please enter your percent of interest in a decimal format: ");
// -----SKIP-----
// } <-- remove
// { <-- remove
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
} // leave this here (end of method)
you are writing instance blocks and in main method,you did not make object creation.instance blocks are executed when you create object of class.if you want to execute those instance block you should write YourClass myclass = new YourClass()in your main method and when you run main function,those blocks outside of main()will be executed OR you should write these blocks in main method just like #shmosel's example.
Related
I'm writing a program for class on inflation over time. The user has to input the price of the item, number of years over which it inflates, and inflation rate. I have all of the variables defined, and some if statements for when the user inputs something less than 0 so it will create an error message. However no matter what I put in, it keeps coming out as the first input error message: "The current price must be at least 0!". I'm pretty new to coding and this is my first class so I'm still not super up to speed on everything. Any help is appreciated, thank you! I'll put my code below:
import java.util.Scanner;
public class inflation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int years, num=1;
double price, percent;
System.out.print("Enter the current price of the item: $");
price = input.nextDouble();
System.out.print("Enter the number of years: ");
years = input.nextInt();
System.out.print("Enter the inflation rate as a percentage: ");
percent = input.nextDouble();
percent = percent/100;
if (price<0); {
System.out.println("The current price must be at least 0!");
System.exit(0);
}
if (years<0); {
System.out.println("The number of years must be at least 0!");
System.exit(0);
}
if (percent<0);{
System.out.println("The inflation rate must be at least 0");
System.exit(0);
}
while (num<=years) {
price = price*(1+percent);
num = num+1;
}
if ((years==0) || (price==0) || (percent ==0)) {
System.out.printf("After %d years, the price will be $%.2f%n", years, price);
}
if (years==1) {
System.out.printf("After %d year, the price will be $%.2f%n", years, price);
}
if (years==2) {
System.out.printf("After %d years, the price will be $%.2f%n", years, price);
}
}
}
We shouldn't use ; after if statement.
Currently you're using like below.
if (price<0); {
System.out.println("The current price must be at least 0!");
System.exit(0);
}
Try to use below snippet in your code. It might help you.
if (price<=0) {
System.out.println("The current price must be at least 0! price");
System.exit(0);
}
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually, monthly, daily;
double balance;
int year = 10 ;
System.out.println("Enter the amount you will like to deposit or type exit to end.");
int deposit = key.nextInt();
annually = deposit * Math.pow((1 + rate/1),year);
monthly = deposit * Math.pow((1 + rate/12),year);
daily = deposit * Math.pow((1 + rate/365),year);
while (deposit)
{
}
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
This is what I currently have. What I am trying to accomplish is to make a loop to add the first outcome with the next one. Also make one formula instead of having three to find the annually, monthly and daily.
First and foremost, asking someone to write out your homework is really unethical, and not helpful for you in the long run. If you don't care about the long run, consider taking a different class. In a career scenario, you're expected to write code on your own.
Secondly, to actually answer your question, here are some tips:
It seems like you want to gather a value (deposit) from the user, and then calculate the Compound Interest for said value. Your program also needs to not exit until the user says to exit. i.e. they want to calculate the CI for a set of numbers.
First step is to check the value from the user. If it is a number, then do calculations on it. If it is a String, then check if it is "exit". In Java, this amounts to writing out an if-statement, and making use of the very helpful "instanceof" keyword. If you haven't learned about that, give this a read, or ask your teacher.
For the calculations part, you simply do calculations on the user's input while the input is not a string set to "exit".
Finally, print out your calculations.
That's it. Your code already has the calculation formulas down, so you just need to code the logic for handling user input.
import java.util.Scanner;
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How much money you want to deposit?");
int principle = sc.nextInt();
System.out.println("what is the rate you want?");
float rate = sc.nextFloat();
System.out.println("After how many years, you want to see your money?");
int year = sc.nextInt();
System.out.println("How many compounds in a year?");
int partialTime = sc.nextInt();
double b = year * partialTime;
double a = 1 + (rate/(partialTime*100));
double x = principle * (Math.pow(a,b));
System.out.println("Your interest in given time would be " + x);
}
}
A couple of suggestions - since you want to check user input against both String and int types, you could define a String type variable to hold the user input, and then do a try/catch to parse it as an Integer, if it's not an Integer check if the input equals "exit" (using the String.equals() method).
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually = 0, monthly = 0, daily = 0;
double balance;
int year = 10, deposit = 0 ;
String userinput = "";
do {
try {
System.out.println("Enter the amount you will like to deposit or type exit to end.");
userinput = key.nextLine();
deposit = Integer.parseInt(userinput);
}
catch (Exception e){
if (!userinput.equals("exit")){
System.out.println("Didn't recognize that input, please try again...");
}
else{
break;
}
}
} while (!userinput.equals("exit"));
annually += deposit * Math.pow((1 + rate/1),year);
monthly += deposit * Math.pow((1 + rate/12),year);
daily += deposit * Math.pow((1 + rate/365),year);
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
Depending on how you want the output, you can easily adjust the scope of the loop to display the amounts after each valid deposit input, or just once at the end, after the user enters "exit".
Hope this helps.
I made a program to calculate total price based on user's input. It is working fine, but i would like to know how to cut the code but to have the same output.
Especially on IF ELSE statement, I would like to know how not to repeat myself in those blocks. Is there any other way I can write ouputs after IF ELSE blocks, or they have to be individually inside of those blocks? Thanks.
Here is the code
import java.util.Scanner;
import java.text.*;
public class GasCalc
{
public static void main(String[] args)`enter code here`
{
double gasPrice,carGallons,fullTank,totalPrice;
Scanner input=new Scanner(System.in);
System.out.print("Do you want to calculate full tank (y/n) ");
String askMe=input.next();
if
(askMe.equalsIgnoreCase("y"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
System.out.print("How many gallons does your vehicle accept ? ");
fullTank=input.nextDouble();
totalPrice=gasPrice*fullTank;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
}
else
if(askMe.equalsIgnoreCase("n"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("How many gallons do you need ? ");
carGallons=input.nextDouble();
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
totalPrice=gasPrice*carGallons;
System.out.println("You will pay "+num.format(totalPrice)+" for "+carGallons+" gallons of gas");
}
}
}
If I understand your question correctly - you don't want to repeat the same code in the 'if' and the 'else' parts of an if statement.
The way you would do this is to the same as anywhere else: extract the common code as a function/method which is called from both places.
You can move the last two statements outside, that way your calculation and printing can be done outside the if-else block.
You can rename fullTank and carGallons to gallons, so both variables have the same name, that way the last two statements can be used outside if-else.
totalPrice=gasPrice*gallons;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
Use a method and factorize the local variable num, used in both if and else :
public class GasCalc {
private static double readDouble(Scanner in, String msg) {
System.out.print(msg);
return in.nextDouble();
}
private static String readString(Scanner in, String msg) {
System.out.print(msg);
return in.next();
}
public static void main(String[] args) {
double gasPrice, carGallons, fullTank, totalPrice;
Scanner input = new Scanner(System.in);
String askMe = readString(input,"Do you want to calculate full tank (y/n) ");
DecimalFormat num = new DecimalFormat("$,###.00");
if (askMe.equalsIgnoreCase("y")) {
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
fullTank = readDouble(input,"How many gallons does your vehicle accept ? ");
totalPrice = gasPrice * fullTank;
System.out.println("You will pay " + num.format(totalPrice) + " for the full tank of gas");
} else if (askMe.equalsIgnoreCase("n")) {
carGallons = readDouble(input,"How many gallons do you need ? ");
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
totalPrice = gasPrice * carGallons;
System.out.println("You will pay " + num.format(totalPrice) + " for " + carGallons + " gallons of gas");
}
}
}
You could actually factorize even more but it would make little sense to create another method for such a specific treatment. If you are using JDK 8 and understand the lambda expressions, go for it.
I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;
package developer;
import java.util.*;
import java.lang.Math.*;
public class Developer
{
static Scanner console = new Scanner(System.in);
String workType; // This will be either an app, or game
String name;
int pay;
int weekPay;
int hrsWorked;
double tax;
public Developer()
{
name = "Ciaran";
}
Developer(String appType, String coderName)
{
workType = appType;
name = coderName;
}// End developer
Developer(String appType, int pay) // Class to choose the pay rate depending on if it is a game or app
{
System.out.println("Are you coding an app or a game? ");
appType = console.next();
if(appType == "app")
{
pay = 20;
}
if(appType == "game")
{
pay = 30;
}
else
{
System.out.println("Please enter either 'app' or 'game' ");
}
}// End developer
Developer(int hrsWorked, double tax, int weekPay, int pay) // Class to choose the tax bracket which the developer is in
{
System.out.println("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
weekPay = hrsWorked * pay;
if(weekPay >= 865)
{
tax = 0.4;
}
else
{
tax = 0.21;
}
}// End developer
Developer(int weekPay, int tax) // Gets the pay after tax
{
weekPay = weekPay * tax;
}// End developer
public void display()
{
System.out.println("This display method works");
System.out.println("User: " + name);
}
public static void main(String[] args)
{
Developer myDev = new Developer();
myDev.display();
} // End main
}// End public class developer
I am trying to get this program to ask the user what their name is; if they are developing a game or app and the amount of hours worked on it. With all this information I want to calculate how much the dev earns including tax. I cannot seem to get the display() method to ask the user the questions though and I have no idea what to do. I am hoping somebody out there can help me.
System.in will read input from the command line. You should wrap it with a java.util.Scanner and nextLine like this:
Scanner scanner = new Scanner(System.in);
String user_input = scanner.nextLine();
Be sure to check
scanner.hasNextLine()
before continuing or you'll get an error.
There are few things that could be done differently in your code, so let's break it down:
1.No need to make console static type, you can use:
private Scanner console = new Scanner(System.in);
2.weekPay is of type int, but your tax is double, if you don't want weekPay to be cast to integer, change it to:
double weekPay;
3.Later on, you are calculating weekPay after tax, so let's introduce a variable for that:
double weekPayAfterTax;
4.All these Developer() methods are constructors, and I think you are slightly confused here. Of course, you can have many constructors, but for us, let's keep only the no-params constructor:
public Developer() {
name = "Ciaran";
//you could initialise all the other variables here as well,
//I'll leave it as an exercise for you :)
}
5.Let's create a method that will ask all the questions and set respective variables:
void setData() {
//let's get the name
System.out.print("What's your name: ");
name = console.nextLine();
System.out.print("Are you coding an app or a game? ");
//since we want the user to enter 'app' or 'game'
//we need to loop until we got these
//we can do this by creating endless while loop,
//which we will end when we have correct input
while (true) {
workType = console.next();
if (workType.equals("app")) {
pay = 20.0;
//stop the loop
break;
}
else if (workType.equals("game")) {
pay = 30.0;
//stop the loop
break;
}
else {
System.out.print("Please enter either 'app' or 'game': ");
//back to top
}
}
//ok, we're out the loop, let's get number of hours
System.out.print("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
//calculate weekPay
weekPay = hrsWorked * pay;
if(weekPay >= 865) {
tax = 0.4;
}
else {
tax = 0.21;
}
//calculate pay after tax
weekPayAfterTax = weekPay - weekPay * tax;
}
6.Let's update our display() method to show all the info:
public void display() {
System.out.println("This display method works");
System.out.println("User: " + name);
System.out.println("Work type: " + workType);
System.out.println("Pay: " + pay);
System.out.println("Week pay: " + weekPay);
System.out.println("Week pay after tax: " + weekPayAfterTax);
}
7.In your main method, you can finally create an instance of Developer class and get the data:
public static void main(String[] args) {
Developer myDev = new Developer();
myDev.setData();
myDev.display();
}
The code above can be improved (such as checking if user entered number where it's expected), and your problem can of course be done differently, but here's the start.
Please check out some tutorials to learn the basics, such as this one, or this one. Most of all, experiment and don't let others put you down for not understanding something.