I'm trying to develop a calculator app in Java. My problem is this:
When I type the digit 1 I see 1, But if I type 1.00 I only see 1.
I wish my user to see 1,234.00 if he types 1,234.00, and not just 1234.
Here's part of my code:
NumberFormat MyNumberForamt = new DecimalFormat("#,###.#####");
String finale = MyNumberForamt.format(Double.parseDouble(Ex1));
resultField.setText(finale);
What can I do?
Note: I am talking about showing the number as the user type it, not at the end of it.
Did you read the docs for DecimalFormat?
....
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
....
Seems like you want to use the format:
new DecimalFormat("#,###.00");
Related
I have to do a String exercise where I have to enter a date like dd/mm/yyyy. Everything works fine except if I enter a space as the input, it prints this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 2, length 1
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3720)
at java.base/java.lang.String.substring(String.java:1909)
at ex5.main(ex5.java:17)
This is my code:
import cs1.*;
public class ex5
{
public static void main(String[] args)
{
String data = "18/08/2011";
//asking for the data
System.out.printf("DATA: ");
data = Keyboard.readString();
//system.out
System.out.printf("DIA: %s %n", data.substring(0, 2));
System.out.printf("MES: %s %n", data.substring(3, 5));
System.out.printf("ANY: %s", data.substring(6, 10));
}
}
My suggestion is that you test whether your input string has length 10. If it is shorter or longer, you know that it cannot have the expected format, so trying your substring calls will make no sense and may cause your program to crash as you have observed.
You need to call data.length(). This method will return the length of the string as an int, for example 10 for 18/08/2011 and 1 for a space. And you need to use an if statement to control that you only call substring() if the returned length is equal to 10. You will probably want an else part in which you issue a friendly message to the user about why your are not printing day, month and year.
This is a very good exercise as it may help you learn something we all have to learn: To validate, to check our input in order to determine whether it fulfils the requirements for the input and whether there is good reason to believe that it is wrong. The clear and strong recommendation is that you always do this.
Please realize that the user may enter any characters and any number of characters when your program asks for a date. Possible inputs include 18/8/2011 (one digit month and therefore too short), 18 d’agost de 2011 (too long) and any nonsense they can dream up. Make your program react as sensibly as possible in each case.
I would like to add that for production code one would use a DateTimeFormatter from the standard library for validating the input and parsing it into a date (a LocalDate).
I am new to Java and using the JIRA MISC Custom Fields add-on and require some logic assistance to solve math functions between two drop down fields.
Field one is "User Cost"
This field contains four string selections with the user price posted at the end of the string.
sam costs .21
mitch costs .419
Lance costs 2.66
xmen costs 13.338
Field two is "Usage"
This field contains two string selections:
24 hours (unless maintenance)
12 Hours (7a-7p)
The argument should be invoked into a new field called "Total User Cost." This field would automatically display the correct price for user and usage amount.
The equation blueprint would be as follows:
Cost*31(calendar days)*usage(12 || 24)
I would want my form to update based on user input selection of these two fields and other variables in my equation.
This is what I have so far:
[
Thank you in advance for any feedback!
If I understand correctly, you first need to initialize issue to something. (It looks red in your images like that variable doesn't exist)
Then, you can do something like this
double costSam = 0.21;
String userSam = issue.get("customfield_10620");
Then, if you are needing to convert or otherwise do some math on userSam, then you need this
double samTotal = costSam * Double.parseDouble(userSam);
Some flaws with your code
You have to define types for your values like String or double.
If you have String x = "hello" on one line, then x = 0.4 on the next, that won't work because of incompatible types
If you did have compatible types on consecutive lines, then the first line is pointless unless using the value from the first, as the second line overwrites the value of the first one
I'm just learning Java and am practicing creating methods and then invoking them in my main program. To practice this I created a simple program that's supposed to gather data from a prospective horse rider.
Here is the main application:
public class CompleteApp {
public static void main(String[] args) {
TaskOne weight1 = new TaskOne();
TaskTwo nameagehealth1 = new TaskTwo();
TaskThree phoneaddress1 = new TaskThree();
if (weight1.Weight() < 250) {
nameagehealth1.NameAgeHealth();
phoneaddress1.AddressPhone();
}
else {
System.out.println("Thanks for checking!");
}
}
}
I've created three separate classes to do different tasks. Here is the class that's having prompting the error:
import java.util.Scanner;
public class TaskThree {
static void AddressPhone() {
Scanner input = new Scanner(System.in);
System.out.println("Please tell me your address: ");
String address = input.nextLine();
System.out.println("Please tell me your phone number: ");
int phone = input.nextInt();
System.out.println("You said your address is " + address + " and your phone is " + phone + ".");
System.out.println("Thank you for the information, we'll be in touch soon to schedule your ride.");
}
}
The error:
Exception in thread "main" java.util.InputMismatchException: For input string: "3037201234"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at TaskThree.AddressPhone(TaskThree.java:10)
at CompleteApp.main(CompleteApp.java:13)
It seems to indicate that the error is in the phone number and that is being read as a String, yet I made it an integer. I'm not sure where I'm going wrong here. Also, how would I handle it if a user entered their phone number like this: 303-720-1234 vs 3037201234?
Thanks so much for the help!
Since it can't be stored as an int due to the length as Sibbo mentioned, and you're concerned about formatting then you should store it as a String. If you have to do any type of checking to make sure the user inputs data in the correct format (either 1234567890 or 123-456-7890) then you should look into regular expressions. If you run a regular expression on your string then you will be able to get a boolean result to tell you whether or not it is valid.
Why not represent the phone number as a String and use scanner.next()? As mentioned before, when a phonenumber start with a 0 this zero would be removed if you use anything other than String, so I think it's the best way to go.
From your comments, I read that parsing it to a Long works for you. I would strongly recommend using a String though, for several reasons:
Phone numbers with leading zeroes (like international phone numbers). Integers and Longs 'trim' leading zeroes, rendering your phone numbers useless.
If you want to do some extra stuff when presenting your phone numbers (like adding dashes or anything), you will have to parse your Integer/Long back to a String and do your representation magic anyway.
As you just found out, not every phone number can be stored in a 32-bit Integer, but you already worked around that using a Long.
There are probably more reasons for this, but these 2 come to mind.
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). Your input value is out of the range of int.
You should store phone number as String rather than int. If you want to handle numbers like 303-720-1234, parse it as string, remove the - character and then use it.
The input 3037201234 is too large to be represented as an int, so it cannot be parsed as an int.
Integers in Java range from −2,147,483,648 to 2,147,483,647.
Instead of using int for variable phone declare it as long and instead of input.nextInt() use method input.nextLong(). I think this will solve your problem.
This question has been answered so please close it...
Thanks for the clarifications!!
I looked at the question above but there is an use case which we should consider before closing the issue:
I have a situation where I raise an order and the system generates a reference number as: 0000002443
I store that number as a string.
When the system sends the order out, it sends two documents. One as a requisition with the above reference number and the other as a Purchase order with a reference: 0000002444
I need to be able to store the first reference number (i.e. 0000002443) as an Integer keeping the preceding zeroes and add +1 and store as a PO reference number (i.e.0000002444) to verify the orders later.
If I keep the first reference number as a String then I won't be able to add 1 to the reference number to get the PO reference Number.
It's a Follow up question:
https://stackoverflow.com/questions/15025136/converting-string-to-integer-but-preceding-zero-is-being-removed
Integers do not have leading zeros (as it says in that other question)
You'd need to convert it to an int, add one, and then pad it back into a String:
def ref = '0000002443'
def refPlusOne = "${ref.toInteger() + 1}".padLeft( ref.length(), '0' )
Simply put, an integer doesn't have a number of leading zeroes. It doesn't even have information about whether it's decimal, hex, or anything like that. It's just an integer.
If you really need to follow your existing design, I suggest you parse it as an integer, add one, and then repad with as many zeroes as you need to get back to the original length.
To be honest, if it's really just meant to be a number, it would be better if you stored it as a number instead of using a string at all.
I'm a beginner in Java, and NetBeans. I'm trying to make a simple program where you introduce 2 numbers and their sum gets divided by two. However, I'm using JFormattedTExtFields and I don't know how to customize the allowed input in them. Basically I'm trying to find out how to:
Only allow numbers to be entered in JFormmatedTextField;
Only allow a certain amount of numbers;
You could use a NumberFormat and specify the maximum number of integer digits with setMaximumIntegerDigits.
Here's a nice article.
Basically you can do something like:
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumIntegerDigits(maxDigitsAmount);
JFormattedTextField field = new JFormattedTextField(f);
The Format should guarantee that the inserted String satisfy the format. Anyway even if a number is supplied, the textfield will store it as a String. So if you need your original Integer you need to rebuild it like suggested #noise:
Integer i = Integer.toString(field.getText());