Java String to Double - java

I recently began to program in Java, and i ran into a little problem:
I already made a String to Double line, but it doesn't seems to work proberly. As you see, the string I want to convert into a Double is one of following: USD, GPB and EURO. I know you can't convert text into a Double, but I already told Java the values of the Strings.
When I run the program below, I get this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "usd" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at Valuta.main(Valuta.java:22)
Why does that happen?
import java.util.Scanner;
public class Valuta {
public static void main(String[] args){
double euro, usd, gpb, done;
Scanner input = new Scanner(System.in);
euro = 7.46;
usd = 5.56;
gpb = 8.84;
System.out.println("DKK to ??");
System.out.println("USD,GPB or EURO?");
String temp = input.nextLine();
System.out.println("amount of dkk??");
Double dkk = input.nextDouble();
System.out.println("mhm");
double donee = Double.parseDouble(temp);
done = dkk*donee;
System.out.println(done);

I think what you want is to be able to associate user input for System.out.println("USD,GPB or EURO?"); to
euro = 7.46;
usd = 5.56;
gpb = 8.84;
One of hte ways to do it is to create a look up Map like this:
Map<String, Double> lookUpMap = new HashMap<String, Double>(){{
put("EURO", new Double(7.46));
put("USD", new Double(5.56));
put("GPB", new Double(8.84));
}};
Then parse user input and look up Double value:
lookUpMap.get(userInput)

The problem is you parse the currency as a double input. This line:
double donee = Double.parseDouble(temp);
should be select the proper conversion factor for the currency. You can do that with a simple if/else, a map or whatever:
double donee;
if ("usd".equalsIgnoreCase(temp) {
donee = usd;
} else if ("gbp".equalsIgnoreCase(temp)) {
donee = gbp;
/* more cases ... */
} else {
throw new RuntimeException("unknown currency");
}
You probably should move that up to before you get the number input, since if it causes an error the number input can't be processed anyway.

You have a couple of problems in this program. First to fix you're error you need to declare type double for the USD, GBP, and EURO variable names that you have there. Second you are going to need to do an if else if else block to determine what conversion to do.
double total;
if(temp.equalsIgnoreCase("USD")){
total = dkk*usd;
}else if(temp.equalsIgnoreCase("GBP"){
total = dkk*gbp;
}else {
total = dkk*euro;
}
System.out.println("This is your converted total " + total);
That will do the conversion that you want it to do. You should also take out Double.parseDouble(temp) because turning that string into a double isn't going to help you.

Related

While loop issues with reading the tokens

I'm trying to read a list of tokens from a text file into separate variables by using a while loop.
Each line in the text file goes: String, Double, Int, Int, Boolean, and there are 11 lines, but I receive an InputMisMatchException for the double line after the String line.
The txt file reads as
AC 120.99 423 70 false
Toaster 18.99 101 30 true
Toaster 11.97 201 100 false
Yoyo 5.99 223 68 false
etc.
I've tried reading the file with .hasNext and .hasNextLine. When changing the double to String I get the error for the next Int and changing that to String again takes the error to the next Int but changing that does not move the exception further.
while (infp.hasNextLine() && count < LIMIT) {
String Product_description = infp.next();
double cost_per_item = infp.nextDouble(); //line 43
int product_id = infp.nextInt();
int quantity_at_hand = infp.nextInt();
boolean domestic_origin = infp.hasNext();
items[count] = new Item(Product_description, cost_per_item,
product_id, quantity_at_hand,
domestic_origin);
count++;
}
It's supposed to read all the tokens into variables and just create separate objects for each line in the text file. But from the error I believe it is only reading the first String then throwing the exception for the double.
The exception on line 43:
Exception in thread "main"
java.util.InputMismatchException at
java.util.Scanner.throwFor(Unknown Source) at
java.util.Scanner.next(Unknown Source) at
java.util.Scanner.nextDouble(Unknown Source) at DB_Master.main(DB_Master.java:43)
as you know nextDouble method is teruning a double value
double nextDouble()
Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is thrown.
try give input in this format
like: 34,2 instead of 34.2
or try convert your Scanner with locale
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method
The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df, and its and DecimalFormatSymbols object, dfs.
for more ref see java docs
still not working try parsing by checking input type.
//************************************************************************
// MixedTypeInput
// This application demonstrates testing before reading to be
// sure to use the correct input method for the data.
//************************************************************************
import java.io.*;
import java.util.Scanner;
public class MixedTypeInput
{
public static void main(String[] args)
{
double number;
Scanner in = new Scanner(System.in);
System.out.println("Enter your gross income: ");
if (in.hasNextInt())
{
number = (double)in.nextInt();
System.out.println("You entered " + number);
}
else if (in.hasNextFloat())
{
number = (double)in.nextFloat();
System.out.println("You entered " + number);
}
else if (in.hasNextDouble())
{
number = in.nextDouble();
System.out.println("You entered " + number);
}
else
System.out.println("Token not an integer or a real value.");
}
}

How to round a user input in Java

I'm attempting to get a user input of a decimal, then round it to two decimal points. This is the code I currently have which is not working correctly, and I'm not sure why.
package code;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalPlaces {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
Scanner qweInput = new Scanner(System.in);
System.out.println("Enter a decimal number:");
String qwe1 = qweInput.next();
df.format(qwe1);
System.out.println(qwe1);
}
}
With scanner, better use nextLine() when you can do it, it preserves from errors with the return line char:
String qwe1 = qweInput.nextLine();
Then you need to parse to double, because if not it tries to cast from Object to double and it crashes
df.format(Double.parseDouble(qwe1));
Then the format method return the string formated, because String are immutable, so you need to print direclty or save it :
qwe1 = df.format(Double.parseDouble(qwe1));
System.out.println(qwe1);
//----------------------------------OR----------------------------------
System.out.println(df.format(Double.parseDouble(qwe1)));
Edit : to avoid parsing to Double you can use nextDouble() from Scanner, as it it would direclty save as a double, but to save the format you would need another String so, with proper name ;)
Instead of
String qwe1 = qweInput.next();
try
double qwe1 = qweInput.nextDouble();
By the way, qwe1 is a terrible name for a variable! Variable names should reflect what they are for.
I would suggest getting the user input as a double and then do this:
double roundNum = Math.round(num * 100.0) / 100.0;

How to indent string and double results in Java?

My question concerns the indentation of the results specifically. Some are String and some double. So far I have the following java program shown at the below. I need the following result:
Name: Yoda Luca
Income: %5000.00
Interests: Swimming, Hiking
I don't want to have to write a prefix for every line. Is there a quicker way to format once for "String" and once for "Double" ?
Program:
import java.util.Scanner;
public class forTesting {
public static void main(String[] args) {
String prefixName = "Name:";
String prefixIncome = "Income";
String Name;
double Income;
//create a Scanner that is connected to System.in
Scanner input = new Scanner(System.in);
System.out.print("Enter name:");
Name = input.nextLine();
System.out.print("Enter income for period: ");
Income = input.nextDouble();
String format = "%-40s%s%n";
System.out.printf(format, prefixName,Name);
System.out.printf(format, prefixIncome, Income);
}
}
String format takes format and followed by n number of arguments.
Yes. %f is for double and you can write them in one shot.
String format = "%-40s%s%n%-40s%f%n";
System.out.printf(format, prefixName,Name,prefixIncome, Income);
And that gives you floating point double. To get it in standard format
How to nicely format floating numbers to String without unnecessary decimal 0?

Java Seperate method to Convert double input to 2 decimal place

I have read many posts in this forum on converting user input to 2 decimal place.
However, I am required to write a method on its own and only be responsible for converting user input to 2 decimal places.
I am currently meeting an error of not being able to convert String to double when doing the decimal conversion.
Below is my current code.
public class LabQuestion
{
static double twoDecimalPlace (double usrInput){
DecimalFormat twoDpFormat = new DecimalFormat("#.##");
usrInput=twoDpFormat.format(usrInput);
return usrInput;
}
public static void main(String[] args)
{
System.out.print("Enter a number on a line: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
twoDecimalPlace("Current input ",d);
}
}
How may I be able to create a method that allows converting to 2 decimal place of a double input from user? Thank you.
You use a NumberFormat object such as a DecimalFormat object to convert a String to a number, which is called "parsing" the String or a number to a String, which is called "formatting" the number, and so you will need to decide which it is you would like to do with this method. It sounds like you want to change the display of the number to show a String representation with 2 decimal places, and so I think that your output should be a String. For example:
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumberFormater {
static DecimalFormat twoDpFormat = new DecimalFormat("#0.00");
static String twoDecimalPlace(double usrInput) {
String output = twoDpFormat.format(usrInput);
return output;
}
public static void main(String[] args) {
System.out.print("Enter a number on a line: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
System.out.println("Output: " + twoDecimalPlace(d));
}
}
Try this:
public Double formatDouble(Number number){
return Double.parseDouble(String.format("%.3f", "" + number));
}

How to print a string with an int

I am trying to get this code to run and basically solve an equation. So, I asked the user to write an equation. It looked like this:
System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine();
But I can't get the user to write a string and an int. Do I need to say String answer or int answer?
An int is used when you want the user to enter a number, but here you're looking for a combination of numbers and other characters, so you will need to use a string. When you have the equation stored in a string, you can use other methods to split up the equation into something solvable, then set int answer to whatever the answer comes out to be.
On a simpler side, String will be required input from the user, User will enter the equation.
Then comes the complex part of solving/computing the equation.
1.) create your own parser to pass operands/operator.
2.) Provide a equation with values to some API, you can make use of MVEL or ANTLR
Here's a little program that demonstrates one way to get the equation and divide into numeric / non-numeric values provided the equation input is space delimited. You can then determine what the non-numeric values are and proceed from there.
import java.util.Scanner;
public class SolveX{
public static void main(String[] a){
Scanner in = new Scanner(System.in);
System.out.println("Write an equation and I will solve for x.");
String input = "";
while( in.hasNext() ){
input = in.next();
try{
double d = Double.parseDouble(input);
System.out.println("Double found at: " + input);
// Do what you need to with the numeric value
}
catch(NumberFormatException nfe){
System.out.println("No double found at: " + input);
// Do what you need to with the non numeric value
}
}
}//end main
}//end SolveX class

Categories

Resources