Get text from textfield - java

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.

Related

Not sure how to use the .equals() method to compare a string in an if statement

System.out.println("\n");
System.out.println("What is the upgrade of your Hammer? You must choose a number.");
System.out.println("1. No Upgrade");
System.out.println("2. Sapphire.");
System.out.println("3. Emerald.");
System.out.println("4. Ruby.");
System.out.println("5. Diamond.");
String var1 = Scanner.nextLine();
//char hammerlevel = (char) System.in.read();
System.out.println();
System.out.println("\n");
double noviceStardustPotion = 6023.33333333; //amount of experience per potion average
if (var1.equals('No Upgrade')
{
}
It was working originally when I used the numbers, but I don't want my users typing a number, I want them to type the actual word.
if (hammerlevel == '1')
{
}
I've researched on the .equals method and I cannot find any examples like mine that use the method with a string in the parentheses
Any ideas or even blatant answers that could help?
First, you're if statement is a bit wonky. It's missing a closing a parenthesis and it should be using " " instead of ' ' to denote a string literal.
if (var1.equals("No Upgrade"))
{
}
And a bit about how equals() works.
String input = "No Upgrade";
String input2 = "no upgrade";
String input3 = "no upgrade";
//this returns false because the strings are not the same value
if (input.equals(input2) {
//do action
}
//this returns true because the string values are the same
if (input.equals("No Upgrade") {
//do action
}
//this returns true because the string values are the same
if (input2.equals(input3) {
//do action
}
The equals method from string is comparing the values of the string. If it has an extra whitespace, an extra capital letter, anything, it won't be true. You can avoid this by using toUpperCase() or toLowerCase() on both strings and then checking their value, or by just using equalsIgnoreCase().
if (input1.equalsIgnoreCase("No Upgrade")) {
}
Cutting down your code to just the relevant bits:
String var1 = Scanner.nextLine();
if (var1.equals('No Upgrade')
{
}
(Everything else is a System.out.println call, or an unused variable)
The only problem with this code is that 'No Upgrade' is not valid Java, and so does not compile: you use single quotes to denote a char literal, and thus you can only have a single character between the quotes, e.g. 'a'.
You use double quotes to specify a String literal:
String var1 = Scanner.nextLine();
if (var1.equals("No Upgrade")
{
}
First, check the input of the user, so the input shouldn´t be something like "you s*ck"
int var1 = Scanner.nextLine().parseInt();
if(var1 == 1){}
if(var1 == 2) //You can also use int, but you don´t want, ok
if (var1.equals("1")) //Because var1 should be a number{}

How do I get user input on a jForm?

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.

Making a substring out of a line read from file

So I am trying to read through a .txt file and find all instances of html tags, push opening tags to a stack, and then pop it when I find a closing tag. Right now I am getting String out of bounds exception for the following line:
if(scan.next().startsWith("</", 1))
{
toCompare = scan.next().substring(scan.next().indexOf('<'+2), scan.next().indexOf('>'));
tempString = htmlTag.pop();
if(!tempString.equals(toCompare))
{
isBalanced = false;
}
}
else if(scan.next().startsWith("<"))
{
tempString = scan.next().substring(scan.next().indexOf('<'+1), scan.next().indexOf('>'));
htmlTag.push(tempString);
}
It is telling me that the index of the last letter is -1. The problem I can think of is that all of the scan.next() calls are moving onto the next string. If this is the case, do I need to just write
toCompare = scan.next()
and then so my comparisons?
You have two major problems in your code:
you're calling scan.next() way too much and as you expect, this will move the scanner to the next token. Therefore, the last one will be lost and gone.
.indexOf('<'+2) doesn't return the index of '<' and adds 2 to that position, it will return the index of '>', because you're adding 2 to the int value of char < (60; > has 62). Your problem with index -1 ("It is telling me that the index of the last letter is -1.") comes from this call: .indexOf('<'+1) this looks for char '=' and if your string doesn't contain that, then it will return -1. A call for #substring(int, int) will fail if you pass -1 as the starting position.
I suggest the following two methods to extract the value between '<' and '>':
public String extract(final String str) {
if (str.startsWith("</")) {
return extract(str, 2);
} else if (str.startsWith("<")) {
return extract(str, 1);
}
return str;
}
private String extract(final String str, final int offset) {
return str.substring(str.indexOf('<') + offset, str.lastIndexOf('>'));
}
As you can see, the first method evaluates the correct offset for the second method to cut off either "offset. Mind that I wrote str.indexOf('<') + offset which behaves differently, than your str.indexOf('<' + offset).
To fix your first problem, store the result of scan.next() and replace all occurrences with that temporary string:
final String token = scan.next();
if (token.startsWith("</")) { // removed the second argument
final String currentTag = extract(token); // renamed variable
final String lastTag = htmlTag.pop(); // introduced a new temporary variable
if (!lastTag.equals(currentTag)) {
isBalanced = false;
}
}
else if (token.startsWith("<")) {
htmlTag.push(extract(token)); // no need for a variable here
}
I guess this should help you to fix your problems. You can also improve that code a little bit more, for example try to avoid calling #startsWith("</") and #startsWith("<") twice.

String to Integer from TextField

Stuck on attempting to convert a String to an Integer. I'm using libgdx & I've tried a few mothods of doing it & I keep getting null in return.
Here is my most recent method I've tried also the easiest.
String x = textfield_1.getText();
String y = textfield_2.getText();
Integer integerfield_1 = Integer.getInteger(textfield_1.getText(), null);
if (integerfield_1 == null) {
System.out.println("Incorrect Integer (Integer Only)");
} else {
System.out.println("Please Enter The Position");
//TODO Fill GUI Form.
}
Anyone have any tips?
Take a look at the JavaDocs for Integer.getInteger(String, Integer) for a sec
Returns: the Integer value of the property.
Or in longer terms...
Returns the integer value of the system property with the specified
name. The first argument is treated as the name of a system property.
System properties are accessible through the
System.getProperty(java.lang.String) method. The string value of this
property is then interpreted as an integer value, as per the
Integer.decode method, and an Integer object representing this value
is returned.
If the property value begins with the two ASCII characters 0x or the ASCII character #, not followed by a minus sign, then the rest of
it is parsed as a hexadecimal integer exactly as by the method
valueOf(java.lang.String, int) with radix 16.
If the property value begins with the ASCII character 0 followed by another character, it is parsed as an octal integer exactly as by the
method valueOf(java.lang.String, int) with radix 8.
Otherwise, the property value is parsed as a decimal integer exactly as by the method valueOf(java.lang.String, int) with radix
10.
The second argument is the default value. The default value is
returned if there is no property of the specified name, if the
property does not have the correct numeric format, or if the specified
name is empty or null.
This is not doing what you think it is...
Instead you should be using Integer.parseInt(String), this will throw a NumberFormatException when the value of the String can't be converted to a valid integer...
For example...
String x = textfield_1.getText();
String y = textfield_2.getText();
try {
Integer integerfield_1 = Integer.parseInt(textfield_1.getText());
System.out.println("Please Enter The Position");
//TODO Fill GUI Form.
} catch (NumberFormatException exp) {
exp.printStackTrace();
System.out.println("Incorrect Integer (Integer Only)");
}
If I understand you, then this
Integer integerfield_1 = Integer.getInteger(textfield_1.getText(), null);
Should be something like Integer.parseInt(String) this -
int integerfield_1 = 0;
try {
integerfield_1 = (x != null) ? Integer.parseInt(x.trim()) : 0;
} catch (NumberFormatException e) {
e.printStackTrace();
}
If you really want to use Integer (the wrapper), then you could use Integer.valueOf(String).
Integer integerfield_1 = null;
try {
integerfield_1 = (x != null) ? Integer.valueOf(x.trim()) : null;
} catch (NumberFormatException e) {
e.printStackTrace();
}

function to identify whether the value can be converted to int, or double, or anything else?

If there is a string variable containing a number string , is there any function to identify whether the value can be converted to int, or double, or anything else?? i need the function name in java
String sent3 = "123";
System.out.println(sent3.matches("[0-9]+"));
System.out.println(sent3.matches("[0-9]+\\.[0-9]+"));// for double
output :- true
If the output is true then it can be converted into int.
Follow this link for more regex
My solution involves trying to parse the string into the various types, and then looking for exceptions that Java might throw. This is probably an inefficient solution, but the code is relatively short.
public static Object convert(String tmp)
{
Object i;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
try {
i = Double.parseDouble(tmp);
} catch (Exception p) {
return tmp; // a number format exception was thrown when trying to parse as an integer and as a double, so it can only be a string
}
return i; // a number format exception was thrown when trying to parse an integer, but none was thrown when trying to parse as a double, so it is a double
}
return i; // no numberformatexception was thrown so it is an integer
}
You can then use this function with the following lines of code:
String tmp = "3"; // or "India" or "3.14"
Object tmp2 = convert(tmp);
System.out.println(tmp2.getClass().getName());
You can convert the function into inline code to test if it is an integer, for example:
String tmp = "3";
Object i = tmp;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
// do nothing
}
I was a little sloppy and tried to catch normal Exceptions, which is rather generic - I suggest you use "NumberFormatException" instead.
String test = "1234";
System.out.println(test.matches("-?\\d+"));
test = "-0.98";
System.out.println(test.matches("-?\\d+\\.\\d+"));
The first one matches (ie prints true) any integer (not int, integer) with an optional - sign in front. The second one matches any double value with an optional - sign, at least one digit before a required decimal point, and at least on digit following the decimal point.
Also, the function name is String.matches and it uses regular expressions.

Categories

Resources