Java have a int value using setText - java

I'm trying to set an int value using jTextField and the setText method. But of course setText wants a String. How do I get round this? I'll give you a snippet of the code:
private void setAllTextFields(FilmSystem e){
getFilmNameTF().setText(e.getFilmName());
lectureTF.setText(e.getLecture());
ageTF.setText(e.getAge());
priceTF.setText(e.getTicketCost());
seatsTF.setText(e.getNoOfSeats());
seatsTF is a jTextField and getNoOfSeats is a method in another class that returns a int value.
Thanks again for answering this question. Now how would I go about getting the value of the int to do something to do?
public void buyTicket() {
String newFilmName = filmNameTF.getText();
String newLecture = lectureTF.getText();
String newAge = ageTF.getText();
String newPrice = priceTF.getText();
int newSeats = seatsTF.
As you can see the code, the String values I can get easy with getText. I can then print them out or whatever with them. How can I do this with the seats int? Thanks again.

String#valueOf convert your int to String.
String.valueOf(e.getAge()); will return the string representation of the int argument.
seatsTF.setText(String.valueOf(e.Age()));
...

USe
seatsTF.setText(""+e.getNoOfSeats());
OR
seatsTF.setText(String.valueOf(e.getNoOfSeats()));

Normal ways would be
seatsTF.setText(Integer.toString(e.getNoOfSeats()));
or
seatsTF.setText(String.valueOf(e.getNoOfSeats()));
but, this can be achieved with a concatenation like this:
seatsTF.setText("" + e.getNoOfSeats());

Assuming age field is of type int, you could try something like:
ageTF.setText( Integer.toString(e.getAge()) );

Setting an int converting it to a String not a big deal. Displaying a value is a problem. To take care of how the value is displayed properly in the textfield you may use a DecimalFormat to format the numeric value. But may be the number is locale specific then you need NumberFormat instance
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumIntegerDigits(12);
nf.setMaximumFractionDigits(0);
nf.setMinimumFractionDigits(0);
String s = nf.format(e.getNoOfSeats());
seatsTF.setText(s);
You may also need to read the tutorial on how to use the DecimalFormat.

To convert Integer Value to String you should
MedicineTM medicine=tblmedicine.getSelectionModel().getSelectedItem();
txtmedicine.setText(medicine.getMID());
txtDescription.setText(medicine.getDescription());
txtQty.setText(String.valueOf(medicine.getQty())); // this is what i did
cmbApproval.setValue(medicine.getApproval());

I think you should write the code as
seatsTF.setText(e.getNoOfSeats().toString());

Related

trouble formatting double in my getter method

my code:
private double retailPrice = 699;
DecimalFormat df = new DecimalFormat("#,###.00");
public double getRetailPrice()
{
return df.format(retailPrice);
}
I am trying to format this for a HW assignment. It's not really required, but I wanted to try this as a learning experience. The method should return a double, but when I try to use decimal formatter, it gives an error:
string cannot be converted into a double
but it's not a string...right?
Basically this ends up as part of a StringBuilder object that is written to a csv file, so it needs to be formatted before it is appended to the StringBuilder.
Do this
public String getRetailPrice()
{
return df.format(retailPrice);
}
You are mixing up two things.
A double number is just that: a number. It does not know about formatting. Formatting is when you turn numbers into strings.
Those are two different things, and there is simply no point in wanting to format a double value whilst keeping it a double. Your code is pointless, plain and simple.
Solution: either have the getter return the double value as it is. Or change its return type to string. And maybe rename it to "getPriceAsFormattedString" for example.
format method return type is String, so you have to parse again formatted value into double. like below
public double getRetailPrice() {
return Double.valueOf(df.format(retailPrice));
}

Printing integer to textfield area

Im having a trouble in java. Im creating a HRRN scheduling. I want to print the integer that I input into a textfield area. Please help me to solve this problem. Thankyou!
private void AWTActionPerformed(java.awt.event.ActionEvent evt) {
int firstprocess=1;
if (bt1.getText().equals("")){
double tempbt1 = Double.parseDouble(bt1.getText());
awttotalprocess = (firstprocess + (tempbt1));
AWTCLICK = 0;
jtf_awt.setText(String.valueOf(awttotalprocess+"ms"));
}
I want to print the awttotalprocess into jtf_awt.
Bracketing issue:
jtf_awt.setText(String.valueOf(awttotalprocess)+"ms");
Many classes come with what's called a .toString() method that prints a pre-specified output when joined with a string. You can concatenate or join a string and a variable -in this case an integer- like this:
int i = 50;
String join() {
return "I'm a string, next is a number: " + 50;
}
Keep in mind that int and Integer are different in that the first is a primitive data type, and the second is the object. This isn't an issue for you in this code but in the future if you try to concatenate a string with an object it may end up printing out the memory address as written in the .toString() default method and would require you to #override the method to specify your own string output. The primitive data types are "easier" to combine and don't require such .toString() overriding or .valueOf() shenanigans.

How to put integer value in JLabel?

I need to display an integer onto JLabel, the following code does not work out well, even with Integer.parse().
How do I rectify it?
JLabel lblTemp = new JLabel("");
lblTemp.setBounds(338, 26, 46, 14);
contentPane.add(lblTemp);
//store int value of item clicked # JList
int temp = list.getSelectedIndex() + 1;
lblTemp.setText(temp); // <- problem
Use String.valueOf method :
Returns the string representation of the int argument.
lblTemp.setText(String.valueOf(temp));
lblTemp.setText(String.valueOf(temp));
Your temp is an integer but the type that the setText(...) method accepts is String. You need to convert first your integer to String.
The quick and dirty solution for putting integers in places that expect strings is to do the following:
lblTemp.setText(temp + "");
I hope this helps.
setText() takes string as an argument. Use this line to code to convert int to string.
Integer.toString(number)
Hope it helps.
If you use Wrapper class Integer instead of primitive type int then you can get temp.toString() method that automatically convert to string value
You can Use String.valueOf() or Integer.toString() Methods
lblTemp.setText(String.valueOf(temp));
or
lblTemp.setText(Integer.toString(temp));

Java - Set a "Int" in a textfield

I'd like to set a int in a textfield to represent a ID. This int will be incremented when the user clicks the button Next. I'm using awt. I tried to do this but it gives a error because it expects a string. :( Is there a solution?
Thanks
Sounds like you will need to keep an internal int variable which you can increment, then update the textfield with the String representation when it's changed. Similarly make sure to update the int if the user manually edits the textfield.
How about public static String String#valueOf(int)
One can convert an int to a String with either
int i = 100;
String s2 = String.valueOf(i);
String s1 = "" + i;
I believe that valueof() is the preferred approach because it can re-use static data for the value.

how can I parse "30.0" or "30.00" to Integer?

I using:
String str="300.0";
System.out.println(Integer.parseInt(str));
return an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "300.0"
How can I parse this String to int?
thanks for help :)
Here's how you do it:
String str = "300.0";
System.out.println((int) Double.parseDouble(str));
The reason you got a NumberFormatException is simply that the string ("300.00", which is a floating point number) could not be parsed as an integer.
It may be worth mentioning, that this solution prints 300 even for input "300.99". To get a proper rounding, you could do
System.out.println(Math.round(Double.parseDouble("300.99"))); // prints 301
I am amazed no one has mentioned BigDecimal.
It's really the best way to convert string of decimal's to int.
Josuha Bloch suggest using this method in one of his puzzlers.
Here is the example run on Ideone.com
class Test {
public static void main(String args[]) {
try {
java.math.BigDecimal v1 = new java.math.BigDecimal("30.0");
java.math.BigDecimal v2 = new java.math.BigDecimal("30.00");
System.out.println("V1: " + v1.intValue() + " V2: " + v2.intValue());
} catch(NumberFormatException npe) {
System.err.println("Wrong format on number");
}
}
}
You should parse it to double first and then cast it to int:
String str="300.0";
System.out.println((int)(Double.parseDouble(str)));
You need to catch NumberFormatExceptions though.
Edit: thanks to Joachim Sauer for the correction.
You can use the Double.parseDouble() method to first cast it to double and afterwards cast the double to int by putting (int) in front of it. You then get the following code:
String str="300.0";
System.out.println((int)Double.parseDouble(str));
Integer.parseInt() has to take a string that's an integer (i.e. no decimal points, even if the number is equivalent to an integer. The exception you're getting there is essentially saying "you've told me this number is an integer, but this string isn't in a valid format for an integer!"
If the number contains a decimal component, then you'll need to use Double.parseDouble(), which will return a double primitive. However, since you're not interested in the decimal component you can safely drop it by just casting the double to an int:
int num = (int)Double.parseDouble(str);
Note however that this will just drop the decimal component, it won't round the number up at all. So casting 1.2, 1.8 or 1.999999 to an int would all give you 1. If you want to round the number that comes back then use Math.round() instead of just casting to an int.

Categories

Resources