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.
Related
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));
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.
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.
[NOTE] Add to the answer below for other good tips for reading the stack trace
I am getting an error in a program that I am making and I don't know how to fix it.
The user has to choose options from messageboxes, and I have to use the users input to calculate the tuition they will have and their discount.
If I run it!
run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Code
package cabrera;
/**
*
* #author Owner
*/
import javax.swing.JOptionPane;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String tuition1 = "", scholar1 = "";
int tuition = 0, scholar = 0;
double discount = 0.0;
JOptionPane.showInputDialog("Input Your Tuition" + tuition1);
JOptionPane.showInputDialog("Choose A Scholar Discount:" + "\n• 1 = 80% " + "\n• 2 = 50%" + "\n• 3 = 25%" + "\n• 4 = No Discount !" + scholar1);
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
JOptionPane.showMessageDialog(null, "Your Total Tuition is: " + tuition);
// If-elseif-else statements based on scholar variable
}
}
How do I fix this error message?
More Info
I recently came across a question that was badly executed. Bad title, bad code, bad question (actually not question, but it could be assumed after some thought). It was from a new SO user.
I wanted to help out and looked at the code for a while. So I edited the post; fixed the code layout, simplified the code, ask the question the OP wanted to ask, etc.... That question is now above; however, the question was put on hold, and I read that questions can take a long time to get off of On Hold. You need something like 5 votes to reopen after it is put on hold. Something I don't see that will happen given that it has been a while since the question was first asked.
I had the answer complete and don't want to waste a good answer
OK, lets look at how to find the issue first!
(3) run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
(2) at java.lang.Integer.parseInt(Integer.java:497)
(1) at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Look at...
(1), here you can see in Main.java you have an issue on line 26
(2), here you can see more information on the issue. In fact you know you have an issue with Integer.parseInt.
You Don't have to worry about looking at this code, because you don't have a class called Integer with method parseInt in the package java.lang
You just know there is an issue here, and it deals with Integer.parseInt which you do call in your Main.java code!
So we located a possible area to check for the error!
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
(3), here we can see that a NumberFormatException was throw because you gave it (the Integer.parseInt that is) an input of "" (an empty string)
So How do you fix it?
First, you have to look at the input of Integer.parseInt
You can see you pass in tuition1 and scholar1
Look to see where those 2 variable are changed / created.
You can see the last thing you did was create those two variables and assigned them the empty string ("")
There is the problem!!
So you need to assign them a value from the user. That will be done via the showInputDialog(...).
the showInputDialog(...) returns a value that you can use! See here!
All you have to do is...
tuition1 = JOptionPane.showInputDialog("Input Your Tuition");
scholar1 = JOptionPane.showInputDialog("Choose A Scholar Discount: 1... 2... 3... 4...")
Take note that tuition1 and scholar1 should NOT be placed inside of the dialog box when you want to assign them values from the user. You need to have the user input some text into the dialog box, and that value will be returned when you press the OK button. So you have to assign that return value to tuition1 and scholar1
You are getting this exception because user is free to enter an input which is not a number. Integer.parseInt(String s) will throw a NumberFormatException if the argument passed to this method is not a valid number. You can restrict the user to input only numbers by the use of regular expressions. The code is below:
String tuition1="";
int tuition = 0;
boolean numFound =false;
try{
while(!numFound){
tuition1 = JOptionPane.showInputDialog("Input Your Tuition:");
Pattern p = Pattern.compile("[A-Z,a-z,&%$##!()*^]");
Matcher m = p.matcher(tuition1);
if (m.find()) {
JOptionPane.showMessageDialog(null, "Please enter only numbers");
}
else{
tuition = Integer.parseInt(tuition1);
numFound = true;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
This will show a message to user "Please enter only numbers", if he tries to enter something that cannot be converted to integer.
import java.util.Scanner;
class Calculator
{
public static void main(String args[]){
Scanner mortgage = new Scanner(System.in);
System.out.println(mortgage.nextLine());
double iRate;
double lAmount;
double answer;
System.out.println("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println(answer);
}
}
My question is I don't think I am declaring the double correctly and am getting an error. How do I declare the double correctly so the program runs without error
That code compiles fine although:
System.out.println(mortgage.nextLine());
seems a bit strange since you wait for a line then print it out. Not sure why you would want to do that.
The following code with that line removed and some cosmetic changes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner mortgage = new Scanner (System.in);
double iRate, lAmount, answer;
System.out.println ("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println ("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println ("Answer is " + answer);
}
}
outputs:
Enter interest rate
10
Enter loan amount
50000
Answer is 50010.0
You may also want to rethink the way in which you do interest rate calculations. Anyone who's ever done work for a bank would get a giggle out of that.
The general way to calculate the interest due on some capital for a given percentage rate would be something like:
answer = iRate / 100.0 * lAmount;
although I realise you may have intended to clean that up once you get past your immediate problem, so apologies for that friendly jab :-)
I'm having to guess since you didn't specify the error, but it's likely coming from your usage of mortgage.nextDouble();. nextDouble(); will read JUST the next double from the line you type in, meaning there will be a trailing newline character at the end, which will result in it behaving in ways you don't expect.
There's a few alternative ways to go about it, so I'll just show one here:
double iRate;
iRate = Double.parseDouble(mortgage.nextLine());
Mind you, this does as much sanity checking as your code (as in, none!). What this does is read in a line of input, and then have the Double class convert the resulting String into a Double, which is stored in the double iRate.
If you want your "Enter interest rate" line to appear first, remove System.out.println(mortgage.nextLine());; it's not doing anything. Your program is waiting for an input before it can proceed, which I think was your problem.
Don't use double's (or float's) for money or any other calculations, have a look at this article "don't use floats for money". basicly it IEEE 754 giving you all kind of rounding errors.