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?
Related
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;
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.
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));
}
This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 8 years ago.
I am a student and i have a little problem with validation inputs.
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
//If name contain other than alphabetical character print an error
double number;
System.out.println("Enter number:");
name = keyboard.nextDouble();
//If number contain other than number print an error
What i have tried is test to parse the string to double but i could not.
I have no idea how to test if the double is only number.
Please give me a clue of what i should do.
You can use Regular expression to check if the input match your constraint as follow :
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
if (!name.matches("[a-zA-Z_]+")) {
System.out.println("Invalid name");
}
String number;
System.out.println("Enter number:");
number = keyboard.nextLine();
if (!number.matches("[0-9]+")) {
System.out.println("Invalid number");
}
Here is a good tutorial to learn regex .
You can loop through each character of the String and check if it's not alphabetic using Character.isAlphabetic(char):
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name:");
String name = keyboard.nextLine();
for (char c : name.toCharArray()) {
if (!Character.isAlphabetic(c)){
System.out.println("INVALID");
break;
}
}
To only accept numbers, you can do something similar using the Character.isDigit(char) function, but note that you will have to read the input as a String not a double, or get the input as a double and the converting it to String using Double.toString(d).
double number = 0;
try {
number = Double.parseDouble(name)
} catch (NumberFormatException ex) {
System.out.println("Name is not a double.");
}
If number is not a double, you can catch a NumberFormatException.
It seems you are using scanner. If you are, you can use the Scanner class' hasNextDouble() to check if the input is a double before reading the double as shown below:
double number;
System.out.println("Enter number:");
if (keyboard.hasNextDouble()){
name = keyboard.nextDouble();
}
Have a look at the Scanner class docs for more information.
There is also the "fancier" regex solution.
Java Pattern Documentation
You can use this (untested code) given you used nextLine() for reading BOTH inputs:
boolean isWordOnly = Pattern.matches("\w*", name); //name is in your code
boolean isFloatOnly = Pattern.matches("\d*.?\d*", number); //number is in your code too
Now the too boolean values tell you if there is the desired format in your input. You can add it in a do - while loop or anything you want.
It is a good idea to start studying reg(ular) ex(presions) because they are useful in string formatting (Imagine that you have to test if the input is a valid email...). Also used to check for SQL injections and many key things in apps and programs generally.
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.