Declaring a Double in Java - java

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.

Related

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ':'

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.

Trying to make a weight converter that converts a weight in kg to stones, pounds and ounces- Java

I would like to create my own Converter class which will take an input weight from terminal and convert it to stones, pounds and ounces. I wondered how I would go about this?
I will create a method within this class called converter, and I wondered whether all my calculations should be within this method or whether I need more methods? I am anxious I haven't gotten the right idea of implementing my own methods yet.
also, would I put the input weight (using EasyIn library)as a parameter for this method?
Any examples would be much appreciated!
Many thanks!
are you trying the console in eclipse or other IDE, than look at system.in
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
welcome to stack overflow. Luckily, all you need to do is write some basic methods that perform math.
public double convertStone();
{
// conversion code here
}
And you can repeat that for each value you need. For the conversion code, you only need to convert the actual math for, say, KG to LBS into code like so:
kgToLbs = kg * 2.21;
Hope this helps!
javaI worked on a project similar to this one. What I did was I posed a question within the terminal asking which conversion they would like to do, which would then prompt some "if" statements that run the selected conversion. This may not be exactly what you're looking for, but it's useful if you're unsure about inputting your own methods.
String selection;
double weight, stones;
Scanner sc = new Scanner(System.in);
//Print statements asking the user what conversion they would like to do
selection = sc.nextLine();
if(selection.equalsIgnoreCase("stones"))
{
//conversion
}
//etc

Why is nextDouble() from the Scanner method sending me "Exception"

I'm suppose to enter 2 numbers, one int that is the amount to withdraw and one double which is the balance (with a space between them). Since every withdraw charges a fee of 0.5, balance must be a double. And thats what must be printed.
I get error at nextDouble, why? I have just 1 month coding, I thought this was going to be a piece of cake, I think BASIC syntax ruined me 30 years ago :(
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//init variables
int amount;
double balance;
//insert amount and balance
Scanner input = new Scanner (System.in);
amount = input.nextInt();
balance = input.nextDouble();
//reduce amount+fee from balance
balance=balance-(amount + 0.50);
//print new balance
System.out.print(balance);
input.close();
}
}
It is dependant on Locale, try to use comma instead of a dot or vice versa.
Ex: 1,5 instead of 1.5
You can check, if there is some int or double to read.
And you have to use , or . depending on the country, you are.
If you need it country independent, read it as string and parse then (see below)
A solotion would be to read the line as a string and parse it then to int and double.
Checking if double is available:
input.hasNextDouble();
Read as String:
String line = input.nextLine();
String[] sl = line.split(" ");
amount = Integer.parseInt(sl[0]);
balance = Double.parseDouble(sl[1]); //solve the problem with . and ,
You also could check if there are enough inputs.

Rounding Decimals in Java

So, I was making a program, where I have the user insert a numerator and denominator, the program converts the pseudo-fraction, to a decimal. It works fine, just one thing. One, if I enter a fraction that is a repeating decimal, (ex. 1/3, 0.3333333...), I want either it say 0.33 repeat, or for irrational numbers, It would round it after let's say 7 digits, and then stop and have "... Irrational" after. How could I do this? Code is below.
package Conversions;
import java.util.*;
public class FractionToDecimal {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
You could use this:
DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.CEILING);
Add as many # as you want decimals and then ou can simply use it like this:
Double d = 12345.789123456;
System.out.println(df.format(d));
Using three # would give you for the example above: 12345.789 for instance.
Please note that you can pick your rounding mode of course.
Small other note: Next time you ask a question on SO, please show some research, there are thousands of post about this and thousands of tutorials online. It would be nice to show what you have tried, what doesn't work ...

JOptionPane.showInputDialog is only showing up once

import java.util.Scanner;
import javax.swing.JOptionPane;
public class moneyRate {
public static void main(String[] args) {
//Get Inputs
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog("How many old pounds? ");
double oldPounds = input.nextDouble();
JOptionPane.showInputDialog("How many old shillings? ");
double oldShillings = input.nextDouble();
JOptionPane.showInputDialog("How many old pennies? ");
double oldPennies = input.nextDouble();
input.close();
//New Pounds calc
double newPounds = ((oldPounds*160.80) + (oldShillings*8.04) + (oldPennies*0.67));
System.out.print("Your old pounds shillings and pennies are equal to £4"
+ "" + newPounds + ".");
}
}
In a programming class we were asked to make a program that would tell the user how much their old pounds shillings and pennies are worth in today's pounds. I had this fully working using the console as input and output for the program, but now when I try to do it using JOptionPane, to present the user with small pop-up boxes it won't work. When I run the task only the first pop-up shows and the program just ends without any form of error message. I'm assuming this is a simple mistake with syntax but I can't spot it.
If anyone spots the mistake, please help me out, thanks :)
The way you are using JOptionPane and Scanner cause the issue.
JOptionPane.showInputDialog("How many old pounds? "); // display this
double oldPounds = input.nextDouble(); // then it wait for scanner input
Now your program will hold there for expecting input from console. You need to change your code as follows
double oldPounds = Double.parseDouble(JOptionPane.showInputDialog("How many old pounds? "));
double oldShillings = Double.parseDouble(JOptionPane.showInputDialog("How many old shillings? "));
double oldPennies = Double.parseDouble(JOptionPane.showInputDialog("How many old pennies? "));
double newPounds = ((oldPounds*160.80) + (oldShillings*8.04) + (oldPennies*0.67));
System.out.print("Your old pounds shillings and pennies are equal to £4"
+ "" + newPounds + ".");
What are you doing there? After you show the Dialog you read from the command line. You should take the value from the inputDialog.
Ruchira answer is complete.. just notice that
JOptionPane.showInputDialog()
returns a string.
That's why you need the Double.parseDouble conversion he put in the code.

Categories