when I compile this code it gives me the error: cannot find symbol > investmentAmount in the last segment. If I take out said segment:
JOptionPane.showMessageDialog(null, "The total amount you have to pay after 5 years is "
+ Math.pow(investmentAmount(interestRate+1),5));
then the rest of the code works, except that I need that segment of the code to pass. If I take out investmentAmount in this segment, but keep interestRate, then the code works perfectly, and gives me the amount after five years. Why does investmentAmount works earlier in the code and not at the end? Why does interestRate not mess up the code at the end and investmentAmount does? Here's the whole code-
import javax.swing.JOptionPane;
public class Ch3IndLabAssignment
{
public static void main( String [] args )
{
String investorName = JOptionPane.showInputDialog( null, "Please enter your first and last name");
JOptionPane.showMessageDialog(null, "Your name is " + investorName);
String input = JOptionPane.showInputDialog( null, "Please enter your investment amount");
double investmentAmount = Double.parseDouble(input);
JOptionPane.showMessageDialog(null, "Your investment amount is " + investmentAmount);
String input2 = JOptionPane.showInputDialog( null, "Please enter the interest rate as a decimal");
double interestRate = Double.parseDouble(input2);
JOptionPane.showMessageDialog(null, "Your interest rate is " + interestRate);
JOptionPane.showMessageDialog(null, "The total amount you have to pay back after 5 years is " +
Math.pow(investmentAmount(interestRate+1),5));
}
}
In the code
JOptionPane.showMessageDialog(null, "The total amount you have to pay after 5 years is "
+ Math.pow(investmentAmount(interestRate+1),5));
You treat investmentAmount as a method with one parameter, which is interestRate+1. Perhaps you meant:
JOptionPane.showMessageDialog(null, "The total amount you have to pay after 5 years is "
+ Math.pow(investmentAmount*(interestRate+1),5));
Notice the *.
You probably meant to write:
Math.pow(investmentAmount * (interestRate+1), 5));
In math, A(B) often means A is multiplied by B. In programming, it often means that A is a function, and B is one of its arguments. The compiler is looking for a method (not a variable) called investmentAmount - since it cannot find a method matching that symbol, you get your "cannot find symbol" error.
Most programming languages, including Java, don't perform implicit multiplication. You're trying to use your variable as a method name. Use * to multiply.
Related
I was trying to run my code with a scanner and suddenly it errors when it goes to the 2nd question.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner stats = new Scanner(System.in);
double base,current;
float bonus;
int level;
System.out.print("Enter the base attack speed: ");
base = stats.nextDouble();
System.out.printf("Enter the bonus attack speed %: " + "%.2f");
bonus = stats.nextFloat();
System.out.println("Enter the level: ");
level = stats.nextInt();
current = (base*1+bonus*level-1) /100;
System.out.print("The character's current speed is: " + current);
}
}
% is what printf (and String.format) use for identifying a placeholder which will be filled in by a parameter provided as second argument.
You therefore have 2 bugs in this code:
The % in attack speed %: is being identified by printf as a placeholder, but you want to print an actual percent symbol. To print that, write 2 percent symbols, which is 'printf-ese' for a single percent symbol: "Enter the bonus attack speed%%: ".
You then add "%.2f" to it which is bizarre, what do you think that does? As written, if you fix the bug as per #1, you immediately get another exception because this requires an argument. The idea is that you can do something like: System.out.printf("The speed of the vehicle in km/h is: %.2f", someValue);. If someValue is, say, 39.8993, that will print the string "The speed of the vehicle in km/h is: 39.90", because you asked for: Print a value as floating point value with max 2 fractional digits. You don't have any input to print there - you're still asking the user, and you can't use this kind of thing to 'format' what the user is supposed to put in. That comes later. So presumably you want to just get rid of that entire "%.2f" thing there.
Code a complete Java program to the following:
if it is a red light violation, then the fine is 1.75 % of the driver annual salary
if it is a speeding violation, then the fine is 1.2 %of the annual salary plus .5% of the salary for every 1 mile/hour over the speed limit.
What you need to do?
prompt user/officer to enter the full name of the driver
prompt officer to enter his/her full name.
prompt user/officer to enter annual salary of the driver.
prompt the officer to enter the type of violation (1 for red light or 2 for speeding)
if speeding then prompt user to enter how many miles/hour over speed limit.
evaluate with a set of if...else how much fine should be assessed, then print a full report including:
name of officer
name of driver
annual salary
violation type (you need to spell it out not just 1 or 2. (Red Light or Speeding)
amount of fine assessed (print a $ sign and round to two decimals)
Also, you must consider the following:
your program must not accept any code other than 1 or 2 for violation type.
your input must be handled by different methods and not in main()
evaluating the fine must be handled in a method of its own.
report must be handled by a different method.
the whole program must repeat for a new driver.
Extra credits: develop your own solution when a driver is subject to both violation…caught speeding and passing when red
Here is my code:
package FinFines_
import java.util.Scanner;
/*
* Description: This program assesses fines for traffic violations.
*/
public class FinFines_
{
static Scanner get = new Scanner(System.in);
//declarations:
static double mph = 0;
static double salary = 0;
static double fines = 0;
static int violation = 0;
static int answer = 1; //1 to continue or 0 to quit
static String officer = " ";
static String driver = " ";
public static void main(String[] args)
{
//input:
while (answer != 0) //while will allow the program to repeat for a new driver
{
input(officer, driver, salary, violation); //call input method
//calculations:
fines = calculateFines(violation, fines, salary, mph); //call calculateFines method
//Output:
disp(officer, driver, salary, violation,fines); //call disp method
//ask user if they would like to continue
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}//end while
System.out.println("Goodbye!");
}//end main
//=================================================================
public static void input(String officer, String driver, double salary, int violation) //Input Method
{
System.out.println("Officer, please enter your first and last name: ");
officer = get.nextLine();
System.out.println("Please the driver's first and last name: ");
driver = get.nextLine();
System.out.println("Please enter the driver's salary: ");
salary = get.nextDouble();
System.out.println("Press 1 if the driver ran a red light. Press 2 if the driver was speeding. Press 3 if the driver is subject to both violations. ");
violation = get.nextInt();
System.out.println("How many miles per hour was the driver going over the speed limit?: ");
mph = get.nextDouble();
}//end input
//=================================================================
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation
{
{
if (violation == 1)
return (salary * 1.75);
else if (violation == 2)
return (salary * 1.2) + (mph * .5 * salary);
else if (violation == 3)
return (salary * 1.75) + ((salary * 1.2) + (mph * .5 * salary));
return 0;
}
}//end calculateFines
//=================================================================
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method
{
System.out.println ("Your name is Officer " + officer + "\nThe name of the driver you pulled over is: " + driver);
System.out.println ( String.format( "The driver's annual salary is $%.2f", + salary) );
{
if (violation == 1)
System.out.println("\nThe type of traffic violation the driver received: Red Light");
else if (violation == 2)
System.out.println("\nThe type of traffic violation the driver received: Speeding");
else if (violation == 3)
System.out.println("\nThe type of traffic violation the driver received: Red Light & Speeding");
}
System.out.println ( String.format( "The amount of fines that will be assessed is $%.2f", + fines) );
}//end disp
}//end class FinFines_
Here is my issue:
When I input values for my program, the program acts as if I didn't input any names or numbers. All it says is
"Your name is Officer
The name of the driver you pulled over is:
The driver's annual salary is $0.00
The amount of fines that will be assessed is $0.00"
What can I do to make sure the program holds my inputted values?
When I press 1, to continue, it skips the first line when it asks for the officer's name. It doesn't allow me to input a name for the variable.
What can I do to make sure my program doesn't skip this line?
Is there an issue with my "return 0;" statement? If I don't include that statement then my program can't run, but I worry that me including it is making my program give 0 to all values.
I noticed that in the calculateFines() method, you have multiplied your values by 1.75. This will give 175% of the original. To find 1.75%, you need to multiply by 0.0175. This is also applicable for all other values.
Hope this helps
Though not a good practice to make everything static. Yet to just make your code work change all your methods as following -
public static void input(String officer, String driver, double salary, int violation) //Input Method {
to
public static void input() {
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation {
to
public static double calculateFines() {
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method {
to
public static void disp() {
This would ensure all your static fields are updated as you call these methods using the same parameters within thei definition and now your main() would include
while (answer != 0) {
input();
fines = calculateFines(); //call calculateFines method
disp();
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}
Note - I've cut short the text and removed comments, please do keep them in your code.
You need to read about the behavior of nextLine(), nextInt(), and nextDouble() regarding new line characters. If any of these leaves a newline character in the input buffer, then the following one will see that character and not consume any further input. This is what you are seeing.
To fix the issue, you need to read the newline character from the Scanner and ignore it. You should look at the Javadocs for Scanner to find an appropriate method to do this.
This is the same issue as #1.
Most likely there is no problem with this return as long as the if statements account for all possible values of violation. In fact, this is a very good solution because it will immediately let you see when violation has an invalid value. You should also learn about enums which allow you to define a finite number of choices for a variable.
I want to make a calculator that greets the user by name then multiplies one number that the user enters and one number that I set. For instance, if the user enters the number 10, I want my code to take the 10 and multiply it by 6.
Here's what I have so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello" + userName + "how many steps do you take in a ten second interval?");
}
}
This part is working, but I can't figure out what to do next.
If you take a look at the Javadoc for Scanner, there is a nextInt() method, which will do the same thing as nextLine() but return an integer. You can set that to an integer variable.
To multiply two variables, it's as simple as
int z = x * y;
Then print out the result, or to simplify it, you could just print out the calculation without setting it equal to a variable
System.out.println("The awnser is: " + (scanner.nextInt() * 6));
Keep in mind, this are integers, you could also use doubles or floats, or even longs. See the scanner documentation for all the methods you can use to get input.
Use nextInt() (or nextDouble() or ...) method to read the number the user will input.
int userNumber = (userInputScanner.hasNext()) ? userInputScanner.nextInt() : 0;
System.out.println("6 * " + userNumber + " = " + (6 * userNumber));
Part B: For Loop Program
Write a program to compute the interest on a bank account. The program will have the following characteristics:
The user will be prompted to input a single line of text containing the deposit amount ($), interest rate (%), and term (in months or years). All items must be separated by whitespace and the input should not be case sensitive. Interest must be compounded monthly. So, some sample (valid) inputs might be:
10000.00 5 36 months
5000.00 4.5 2 years
45000.00 5.0 24 Months
If the user has made an input error, you need to inform them of the error and prompt them to re-enter the information. Primary error conditions are:
Term specified that is not “months” or “years”.
If values for interest rate or term time ≤ 0.
For this program, you must use the FOR loop construct to compute the interest.
You must make sure that interest is computed properly for monthly compounding. If you don’t know what “compound interest” is, Google it. One such site is here.
Once you have verified that the data is properly entered, compute and print out the interest payment on a month by month basis.
At the end of the program, print out the beginning balance, final balance, and the cumulative interest earned. Make sure to clearly label each output.
The code written so far is:
import java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double principal = 0;
double rate = 0;
double time = 0;
double compoundInterest = 0;
System.out.print("Enter the Principal amount : ");
principal = input.nextDouble();
System.out.print("Enter the Rate : ");
rate = input.nextDouble();
System.out.print("Enter the Time : ");
time = input.nextDouble();
compoundInterest = principal * Math.pow((1 + rate/100), time);
System.out.println("");
System.out.println("The Compound Interest is : "
+ compoundInterest);
}
}
But I don't know how to get input from the user.
You could use the Scanner nextLine() method to read in an entire line of input from the user at once, but then you'd have to tokenize that line and convert each token to the correct data type. It's easier to code and more clear to the user if you ask for one input at a time the way you have it.
I'm making a app something like a banking app however I want the user to enter their pin e.g. 1111 and hit enter, then if the pin is correct users name and balance will be displayed if the pin is wrong "wrong pin!" message will be displayed.
I'm struggling to make the correct pin work, every number I enter prints out the "wrong pin" message rather than the name and balance.
code I used for enter button:
int moInt = 1111;
String moString = "1111";
String intAsString = Integer.toString(moInt);
double balance = 10000.00;
if (moString.equals(moInt)) {
System.out.println("Hi Mohamed" + "\nYour balance is" + " £" + balance);
ATM a = new ATM();
a.setVisible(true);
a.setResizable(false);
} else{
System.out.println("Wrong Pin!");
}
I tried this
if (moString.equals(moString)) {
System.out.println("Hi Mohamed" + "\nYour balance is" + " £" + balance);
ATM a = new ATM();
a.setVisible(true);
a.setResizable(false);
this prints out the name and balance however it does that with any number.
the specific pin or number am trying to use is 1111.
HELP PLEASE been stuck on this for AGES!!! :'(
Look at moString.equals(moInt), this equates to String.equals(int), which will never be true...
You probably meant to use moString.equals(intAsString )
FYI- From a security point of view, String is not a good choice for storing sensitive data, either maintain it in a char array or as it's a number, as an int value
In Java, integers and strings are as separate as can be. No integer can be equal to a string.
What you have to do is convert the string to an integer, then compare it to the other integer. Change the if to this:
if (moInt == Integer.parseInt(moString))