I can use numbers and stuff like
num1 = Float.parseFloat(txt1.getText());
but I am looking to get words from a text field, then do calculations based on which word. Like:
String input1;
if (input1.equalsIgnorecase("Word")) {
2 + 2; }
I just don't know how to do that on a jform.
As pointed out by #MadProgrammer, .getText() will help you in retrieving String values from a test field.
For example, If your Java Form contains a text field whose variable name is jTextField1, you can retreive value from it by:
String input1 = jTextFielf1.getText();
Just for information,
float num1 = Float.parseFloat(txt1.getText());
also does the same thing, it first gets the string value from the text field and converts it into a float value.
Related
I need to store an integer value into database, so I need to convert the value of the textfields into integers and for some reason I'm getting this exception:
java.lang.NumberFormatException: Invalid int: "android.widget.EditText{431fbec VFED..CL. ........ 0,250-1080,386 #7f0b0076
I set the editText to be number type, but when I want to add the value of that field to the integer variable I get the exception above.
Integer year = Integer.parseInt(editTextYear.toString());
This line of code is the problem; I tried to first create the string and then parse the value to int but it doesn't work.
Use getText() property to get input from EditText. toString() property on object will return you object representation in String form.
final String input = editTextYear.getText().toString(); // To get input and
// then parse it
if(input!= null)
Integer year = Integer.parseInt(input);
Rasi is essentially right, but I'd use isEmpty instead of null.
So instead of
editTextYear.toString()
it should be
editTextYear.getText().toString()
but to avoid a nullpointerexception, just do:
if(!input.isEmpty)
to avoid having either an empty or a null value there
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.
This question already has answers here:
Most efficient way of converting String to Integer in java
(11 answers)
Closed 7 years ago.
My assignment is to create a randomly generated number, ask the user to enter a number, then compare the two and show a messagebox telling whether or not they match. This is my code so far...
import javax.swing.*; //GUI components
public class RandomGuessMatch {
public static void main(String[] args) {
Integer random = (1 + (int)(Math.random() * 5)),
userNum;
// Get the input
userNum = JOptionPane.showInputDialog("Enter a number 1 - 5.");
//Checks to see if numbers match
boolean matches = (random == userNum);
JOptionPane.showMessageDialog(null, "The random number is " + random + ". " + "Does it match? " + matches);
}
}
The only error I'm getting is when I'm trying to get the user input. "Cannot convert from String to Integer". But, I'm having trouble figuring out how to just get the user's number and correlate it to "userNum" so that I can compare it with "random". Any help?
JOptionPane's showInputDialog method returns a String. What you can do is use the resultant string as an argument in the Integer class's constructor:
userNum = new Integer(JOptionPane.showInputDialog("Enter a number 1 - 5."));
Additionally, since you are using Integer objects, you must use the equals method to compare them:
boolean matches = random.equals(userNum);
You can convert from String to Integer trough the parse.
int x = Integer.parseInt("1");
Note that this throws an Exception if the String is NaN
You need to cast your string response into an Integer using
Integer.parseInt(userChoice)
You can get the input this way:
userNum = Integer.getInteger(JOptionPane.showInputDialog("Enter a number 1 - 5."));
Later you can do some input validation to prevent non Integer input.
ShowInputDialog will return a String. Therefore, the variable that you put its value into must also have type String.
Try making a variable called "userInput" and put the value that the user enters in there. Then you can say
userNum = Integer.valueOf(userInput);
From there, compare the two Integers using "userNum.equals(random)". The double equals operator will only work on int types, not Integers.
If you read a user input it is a String, so you have to declare userNum as a String instead an Integer.
String userNum;
The next step is to compare your random number with the String. To do that you need the method Integer.valueOf(String s), so they will be both Integer values:
boolean matches = (random == Integer.valueOf(userNum));
Have fun :)
I'm making a GUI program. In my first program I have the following code:
double num1;
num1 = Double.parseDouble(guess.getText());
I believe that this code gets the value from the text field and converts it to double.
How can I get the value and convert it to String or Char?
Since the getText() already returns a String, storing its value as a String is trivial.
In order to parse a double, you've already done it, just watch for the NumberFormatException, in case of invalid input.
To store its value as a char, that depends on your requirements. Do you want the first character? Do you require the string to have only a single character? Is any character valid? And so on.
// Storing the value as a String.
String value = guess.getText();
// Storing the value as a double.
double doubleValue;
try {
doubleValue = Double.parseDouble(value);
} catch (NumberFormatException e) {
// Invalid double String.
}
// Storing the value as a char.
char firstChar = value.length() > 0 ? value.charAt(0) : (char) 0;
// Require the String to have exactly one character.
if (value.length() != 1) {
// Error state.
}
char charValue = value.charAt(0);
use String.valueOf() instead of Double.parseDouble() this will help you convert double into string value
The getText() already returns the text as String.
Btw, be careful of Exceptions due to parse error. But your on the right track. :)
The getText()method returns a String. when you use .parseDouble what you are really doing is turning the string the user entered and into a double therefore in the case of a string you do not have to use a .parse method because the value called is already a string. In the case of a character you would have to use something like this:
String text = jTextField1.getText();
if (text.length() > 1 && !text.contains(" ") && !text.contains(",")) {
//make sure that its length is not over 1, and that it has no spaces and no commas
char ch = text;
} else {
//if a space or comma was found no matter how big the text it will execute the else..
System.out.println("this is not allowed");
jTextField1.setText("");
}
The getText() function already fetches a String value from the Textfield.
For example:
String var = guess.getText();
Here, var is storing the String value received from the Textfield.
In my code, I'm asking the user to input three different values divided by a blank space.
Then, those three different values I would like to assign them to three different Double variables.
I have tried by assigning the first character of such string to my double variables but I haven't been able to succeed.
Any suggestions?
Thank you!
Here is what I'm trying to do:
int decision = message();
String newDimensions;
double newHeight, newWidth, newLength;
if(decision == 1){
newDimensions = JOptionPane.showInputDialog("Please enter the desired amount to be added" +
"\nto each dimension." +
"\nNOTE: First value is for Height, second for Width, third for Length" +
"\nAlso, input information has to have a blank space between each value." +
"\nEXAMPLE: 4 8 9");
newHeight = Double.parseDouble(newDimensions.charAt(0));
Take input from user.
split that line using delimeter space i.e " ".
inside for loop change each index element to double.By using Double.parseDouble(splitted[i]);
Get the input, split it by a whitespace and parse each Double. This code does not sanitize the input.
String input = "12.4 19.8776 23.3445";
String[] split = input.split(" ");
for(String s : split)
{
System.out.println(Double.parseDouble(s));
}
You could first split the input using String.split and then parse each variable using Double.parseDouble Double.parseDouble to read them into a Double variable.
String[] params = newDimensions.split(" ");
newHeight = Double.parseDouble(params[0]);
newWidth = Double.parseDouble(params[1]);
Double#parseDouble(str) expects a string,and you are trying to pass a character.
try this:
newHeight = Double.parseDouble(newDimensions.subString(1));
Try something like this:
newDimensions = JOptionPane.showInputDialog(...
newDimensions = newDimensions.trim();
String arr[] = newDimensions.split(" ");
double darr[] = new double[arr.length];
for(int i=0;i<arr.length;i++) darr[i] = Double.parseDouble(arr[i].trim());
There are still some defensive issues that can be taken. Doing a trim on your parse double is kind of critical.