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

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.

Related

How to make scanner scan multiple inputs from one scanner line in java?

The user should be able to input data of 5 customers with balances. However this piece of code only works for 1. I initially thought of using a for OR a while loop but I think they will create the display message 5 times.
import java.util.Scanner;
public class Assignment {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
Customer c [] = new Customer [5];
Customer hold;
String name; int count = 0;
double totalBalance = 0.0;
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
System.out.println("Search for all customers who have more than $100");
for (int i=0; i<count ; i++){
if (c[i].getBalance()>100)
System.out.println(c[i].getName());
totalBalance += balance;
averageBalance = totalBalance/5;
System.out.println("The average balance is: "+averageBalance);
}
}
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
for(int i=0; i<5; i++){
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
}
So, in the above code the display message prints 5 times but every time it will be for different customers. For e.g.
Enter 1 customer name and balance
John
20.0
Enter 2 customer name and balance
Jim
10.0
and so on.
I hope this helps. If you ask me you should be using java.util.ArrayList or java.util.LinkedList. These classes come with many features out of the box and you need not code much as in the case of arrays.
You are asking is not a coding problem but just a matter of design.
For what you are doing as per design you can follow below process or similar.
Enter comma separated user names in single line.
Read the line and split the names, now you have x customers detail like name read in a single shot.
Now you have names, repeat 1-2 above for every type of detail just need to be entered comma separated. Try to take one type of detail at a time, i.e. one, line one detail like salary of emp or department.
for pseudo code:
private String[] getDetails(BuffferReader reader){
// read a line at a time, using readline function
// using readed line/console input, split it on comma using split() function and return array of values.
}

Bank Interest using a for loop

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.

Java double input

I am trying to let the user freedom of entering a number at his own style like he can choose to enter 2 or 2.00 but as you know the double cannot accept this (2). i want the double to accept this with 2 decimal places only (basically i am representing money).
this is what i am not sure how to take the input and convert that in to the 2decimals format. New to java.tks
Tried google but cant find where i can format at the input itself, means dont even let the user type any more decimal places other than 2decimal places, not post-process after entered in to multiple different variables., tks
public static void add()
{
double accbal;
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Enter account balance");
accbal = sc.nextDouble();
//this is the part where i need to know the entered value is formated to only 2 decimal places
}
Since showing decimal places is really a formality to the end user, you could read your value in as a String instead and convert it to a Double or BigDecimal, the latter being preferred if you're working with actual finances.
Related: What Every Computer Scientist Should Know About Floating-Point Arithmetic
public static void add() {
BigDecimal accbal; // could declare a Decimal
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Enter account balance");
accbal = new BigDecimal(sc.nextLine());
System.out.println(df.format(accbal.doubleValue()));
}
Try this:
DecimalFormat df = new DecimalFormat ("#.##");//format to 2 places
accbal = sc.nextDouble();
System.out.print(df.format(aacbal));//prints double formatted to 2 places
however I see you say:
Tried google but cant find where i can format at the input itself,
means dont even let the user type any more decimal places other than
2decimal places
If the above is your intention for whatever reason then simply read in the input using nextLine() and then check to make sure after the decimal point it only has a length of 2:
double accbal=0;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter account balance");
String s = sc.nextLine();
if (s.substring(s.indexOf('.') + 1).length() <= 2)//accept input and convert to double
{
accbal = Double.parseDouble(s);
break; //terminates while loop
} else {
System.out.println("Incorrect input given! Decimal places cant exceed 2");
}
}
System.out.println("Balance: "+accbal);
If you want to accept input of the form "#.##" just specify a custom regex for Scanner.hasNext :-)
final Scanner input = new Scanner(System.in);
final Pattern pattern = Pattern.compile("\\d+\\.\\d{2}?");
while (input.hasNext()) {
System.out.println((input.hasNext(pattern) ? "good" : "bad")
+ ": " + input.nextDouble());
}
Using the following input:
2.00
3.14159
2
The result is: (also found here)
good: 2.0
bad: 3.14159
bad: 2.0
This way allows you to verify they enter an amount with two decimal places.
Even though you said you do not want a mere post-processing solution, in case you already have an amount and wish to convert it to use 2 decimal places, and you're focused on precision (since this is money), maybe try using BigDecimal -- in particular, see BigDecimal.setScale:
while (input.hasNextBigDecimal()) {
System.out.println(input.nextBigDecimal().setScale(2, RoundingMode.HALF_UP));
}
The output is thus:
2.00
3.14
2.00

Declaring a Double in 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.

How do you input from a text file that contains multiple datatypes

Java newbie here, I have a problem that I have been banging my head on the wall for several hours now.
Basically, I need to read a text file that contains String, Integer, and Double datatypes. (see below for the file)
The text is formatted in two lines. The first line is only the product name, and the second line is an integer representing the factory number, and then 4 decimals that represent the sales in one of four factories in millions of dollars.
CrossTrainMax
1 15.1 12.8 3.14 2.3
AirGlider
3 12.2 4.6 6.5 8.3
AquaWalker
2 3.82 1.75 7.6 6.38
SuperHike
1 9 11.2 7.5 8.4
The first value is the name of a product. The single digit integer is a factory number where it is produced. The decimal number are the sales of that product in millions of dollars, delimited by a white space.
My plan is to read in the product name as a string, and then use the integer value as a SWITCH statement.
(The % of profit is different at each factory, so I thought the best way to go about solving this way to calculate the total profit inside the switch statement.)
After I get the total sales per product, I will then have to display to the user which product has the highest sales.
So my questions are:
a) How can I read in multiple data types if I am trying to do it line by line using NextLine?
I know how to read in all integers, all doubles, or all strings, but what is the best way to go about it if they are all different?
My attempt so far has resulted in mismatch exceptions.
b) Am I better off reading all of the values in as strings and using regular expressions to parse them into variables?
c) If I am going to be sorting the Sales based on the highest profit, will I need to store each products total sales in a separate variable? Is it possible to do this if I am reading in the input of the file using loops? (We have not covered arrays yet)
Here is the beginning of the code I have been playing with. I am still stuck on the problem of reading the separate data types in. Any feedback/ criticism is appreciated.
import java.util.Scanner; // Needed for scanner class
import java.io.*; // Needed for the File and IOException
public class SalesProcessor
{
public static void main(String[] args) throws IOException
{
int x;
double sales = 0;
double total = 0;
double profit = 0;
// Create scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine( );
for (x = 1; x <= 5; x++)
{
while (line != "END")
{
int plant = inputFile.nextInt();
switch (plant)
{
case 1:
while (inputFile.hasNext())
{
sales = inputFile.nextDouble();
total = total + sales;
}
profit = sales * .06;
System.out.println(total);
System.out.println(profit);
System.out.println(profit);
break;
}
}
}
}
}
In general, you need to use the java tokenizer per a friend.

Categories