Period in output double but comma in input double? - java

I wrote a simple calculator in java, which takes two numbers of type Double from the user and outputs the sum. When I i input the numbers with periods (2.0) I get errors. But when I input with a comma (2,0) it works! It then outputs the answer in the form of 2.0.
Why does my java recognize a double input by comma, but outputs it with a period? The video tutorial I followed, the guy input his double with periods and got it output with periods..
this is my code:
import java.util.Scanner;
public class ScannerIntro {
public static void main(String args[]){
Scanner bucky = new Scanner(System.in);
double firstNumber, secondNumber, answer;
System.out.println("Enter first number: ");
firstNumber = bucky.nextDouble();
System.out.println("Enter Second number: ");
secondNumber = bucky.nextDouble();
answer = firstNumber+secondNumber;
System.out.println("The answer is:");
System.out.println(firstNumber+" + "+secondNumber+" = "+answer);
}
}

The way the input is interpreted by nextdouble (Class Scanner) depends on the locale you're at:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
In some countries (like France or Germany, a period is used as thousands-separator while the comma is used as decimal Point.
The output is from a different class that uses the default way.
You could either
1) Set the locale for your Scanner so it matches the output. For this use the function:
useLocale(Locale locale)
2) Set the format printf does Format your numbers:
From the docs:
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
public PrintStream format(Locale l, String format, Object... args)
Both ways will work. Now you have to decide which is the preferred one for you.

Related

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?

Simple try & catch code for scanning not working with decimal values

import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner a = new Scanner(System.in);
System.out.println("Enter a number: ");
try{
float b = a.nextFloat();
System.out.println("You wrote " + b);
}catch(Exception n){
System.out.println("That wasn't a number, yo!");
}
a.close();
}
}
I want to scan the number that the user has entered and hence figure out whether it is a number or not. Problems arise when I enter a decimal number such as 3.1415 because it detects it as a non-numerical value.
It is because the Scanner parses the float depending on your locale. When you use a , instead of a . it works. For example, in Germany and Austria, it is common to use a , as comma, not a . so depending on where you are, this might be the case as well.
You can set the locale of the Scanner to US using:
a.useLocale(Locale.US);
Then you'll have to use . again.

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

.useDelimiter to parse commas but not negative sign

So I have looked at a couple of related questions, but still can't seem to find my answer (I guess because it's specific). I'm trying to use the Scanner.useDelimiter method in Java and I can't get it to work properly... here is my dilemma...
We are supposed to write a program that takes a X, Y coordinate and calculates the distance between the two points. Obviously, one solution is to scan for each x and y coordinate separately, but this is sloppy to me. My plan is to ask the user to input the coordinate as "x, y" and then grab the integers using the Scanner.nextInt() method. However, I have to find a way to ignore the "," and of course, I can do that with the useDelimiter method.
According to other threads, I have to understand regex (not there yet) to put in the useDelimiter method and I've got it to ignore the commas, HOWEVER, there is a possibility that a user inputs a negative number as a coordinate (which is technically correct). How do I get useDelimiter to ignore the comma, but still recognize the negative sign?
This is my first time on here, here is my code:
import java.util.Scanner;
import java.text.DecimalFormat;
public class PointDistanceXY
{
public static void main(String[] args)
{
int xCoordinate1, yCoordinate1, xCoordinate2, yCoordinate2;
double distance;
// Creation of the scanner and decimal format objects
Scanner myScan = new Scanner(System.in);
DecimalFormat decimal = new DecimalFormat ("0.##");
myScan.useDelimiter("\\s*,?\\s*");
System.out.println("This application will find the distance between two points you specify.");
System.out.println();
System.out.print("Enter your first coordinate (format is \"x, y\"): ");
xCoordinate1 = myScan.nextInt();
yCoordinate1 = myScan.nextInt();
System.out.print("Enter your second coordinate (format is \"x, y\"): ");
xCoordinate2 = myScan.nextInt();
yCoordinate2 = myScan.nextInt();
System.out.println();
// Formula to calculate the distance between two points
distance = Math.sqrt(Math.pow((xCoordinate2 - xCoordinate1), 2) + Math.pow((yCoordinate2 - yCoordinate1), 2));
// Output of data
System.out.println("The distance between the two points specified is: " + decimal.format(distance));
System.out.println();
}
}
Thanks for your help and I look forward to helping other people down the line!
I think it would be easier (and more conventional for the command line type of programs) to just ask for x and y separately
Example:
Scanner myScan = new Scanner(System.in);
System.out.print("Enter your first x coordinate: ");
xCoordinate1 = Integer.parseInt(myScan.nextLine());
yCoordinate1 = Integer.parseInt(myScan.nextLine());
However if you insist on doing both at the same time and using a delimeter you could try using the return line as a delimeter instead of the ", " because you would have to delimit it twice remember, once after x and then again after y. But that sort of brings you back to the same result. The problem is that you need to delimit it twice if you want to use a delimeter and take it in at the same time. I'd suggest taking a look at the .split function of a string instead.
Another approach would be to use the .split(", "); function where ", " is your delimiter.
Example:
Scanner myScan = new Scanner(System.in);
System.out.print("Enter your first coordinate (format is \"x, y\"): ");
String input = myScan.nextLine();
xCoordinate1 = Integer.parseInt(input.split(", ")[0]);
yCoordinate1 = Integer.parseInt(input.split(", ")[1]);
Hope this helps, Enjoy.

Categories

Resources