Converting from String to Int - java

I'm trying to validate my program by entering a value through a JTextField on a JDialog and if it's less than a value..., else do ... I keep running into a problem on the line:
int intDiagInput = Integer.parseInt(dialogInput)
JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
dialogInput = dialogPaneInput.getText(); //get info from JTextField and put in string
int intDiagInput = Integer.parseInt(dialogInput); //convert string to int
Any help would be greatly appreciated.

Your code is wrong in two ways:
The first paramenter you pass to showInputDialog is used as the parent, just for layout purposes, it has nothing to do with the actual content of the input dialog. Therefore your second error is getting the text from the displayed dialog.
To get the text the users enters you need to write something like:
String dialogInput = JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
int intDiagInput = Integer.parseInt(dialogInput ); //convert string to int
What you are doing is getting the text of some magical object dialogPaneInput, which probably is just an empty string.
Additionally you should check that the user inputs a valid number, not in terms of a number that you would accept but in terms of it actually beeing a number, otherwise you will run into the already existent NumberFormatException - or wrap the parsing in a try...catch-block.
try {
int intDiagInput = Integer.parseInt(dialogInput );
} catch (NumberFormatException nfex) {
System.err.println("error while trying to convert input to int.");
}

The exception you posted on the comment section (java.lang.NumberFormatException: For input string: "") means that you're trying to convert an empty String to int.
Change your code to verify if dialogInput is not empty before converting it to int.

Related

How would I initialize a string in Jframe?

I'm fairly new to programming, and I can't seem to figure out how to initialize a String on JFrame Form. I do not know what code to put in to initialize the String if the contents of the string is entered later, by the user. This basically means that the String (stringone) is currently a blank text field on my form. The user enters a sentence or string and the label (one) tells how many characters are in the string they just entered. Here is my code so far:
{String stringone = new String ();
int one;
one = Integer.parseInt(txtstringone.getText());
one = (stringone.length());
lblone.setText(String.valueOf(one));}
Currently there is a yellow line under the third line of code, saying it may not have been initialized. It also does not work when I run it. Hope this clears it up!
Thanks so much in advance!
Try this:
String stringone;
Remove new String()
If you want to initialize it, tou must pass it a String value. For example:
String stringone = "value";
The string's length (stringone.length()), will be 5.
So, in order to take the length of a String you must first initialize it. Otherwise, it will be null, and null does not have length.
The user enters a sentence or string and the label (one) tells how many characters are in the string they just entered.
What you need to do is add an event handler for when the user has entered the string. There is no "user entered string" before the user has given the string.
An event handler is code that runs when some "event" occurs. A user writing in a field is a possible event.
Here's how you can add an event listener on your txtstringone text field component. It will be triggered when the user presses the Enter key.
txtstringone = new JTextField();
txtstringone.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
String text = txtstringone.getText();
int one = text.length();
lblone.setText(String.valueOf(one));
}
});
You can find a longer tutorial at https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html and a short working program at https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextDemoProject/src/components/TextDemo.java

How to fix java.lang.reflect.InvocationTargetException when using integer.parseint

Im trying to make a simple calculation program but i keep getting this error whenever I try to run the code. How can i avoid this?
TextField inputOne = new TextField("Input first data");
// Making output 1
int inputNumber = Integer.parseInt(inputOne.getText());
Always get error message java.lang.reflect.InvocationTargetException
at line 25 where the parse int is placed
getText() function returns the input value of the user, or the "Input first data" String? if it returns the input value of the user then it is probably a NumberFormatException that you should handle, else it is because the String mentioned is the mistake.

Java dynamic var assigned to variable

I have a chicken and egg issue of sorts. I'm use to dynamic typing (python) so please be gentle on me if this is a basic thing.
I have a scanner, but I want to allow the user to enter either a string or an integer (1 or 'option1'). Because it's a user input, I don't know the resulting type (int or string). I need to get the user input from the scanner, assign it to a variable, and then pass that variable to an overloaded method.
The problem is that I need to declare the variable type. But, it can be either. How do I handle this?
EDIT
To clarify, I was thinking of doing something like this (Below is pseudo code):
public static float methodname(int choice){
//some logic here
}
public static float methodname(String choice){
//some logic here
}
Scanner input = new Scanner( System.in );
choice = input.nextLine();
System.out.println(methodname(choice));
The problem that i'm having is the declaration of 'choice'. What do i put for the type?
You can take it as a String and try to convert it to an int. If the conversion happens without problems you can use the int version, otherwise use the String version.
String stringValue = ...
try {
// try to convert stringValue to an int
int intValue = Integer.parseInt(stringValue);
// If conversion is possible you can call your method with the int
call(intValue);
} catch (NumberFormatException e) {
// If conversion can't happen call using the string
call(stringValue);
}
Take the input value as String, convert it to integer using
String number = "1";
int result = Integer.parseInt(number);
if it parses then you can continue using it as a number. And if it fails it will throw NumberFormatException. So you can catch the exception and proceed it with string.
try{
String number = "option1";
int result = Integer.parseInt(number);
// proceed with int logic
} catch(NumberFormatException e){
// handle error and proceed with string logic
}

How to read NumberFormatException error message?

[NOTE] Add to the answer below for other good tips for reading the stack trace
I am getting an error in a program that I am making and I don't know how to fix it.
The user has to choose options from messageboxes, and I have to use the users input to calculate the tuition they will have and their discount.
If I run it!
run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Code
package cabrera;
/**
*
* #author Owner
*/
import javax.swing.JOptionPane;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String tuition1 = "", scholar1 = "";
int tuition = 0, scholar = 0;
double discount = 0.0;
JOptionPane.showInputDialog("Input Your Tuition" + tuition1);
JOptionPane.showInputDialog("Choose A Scholar Discount:" + "\n• 1 = 80% " + "\n• 2 = 50%" + "\n• 3 = 25%" + "\n• 4 = No Discount !" + scholar1);
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
JOptionPane.showMessageDialog(null, "Your Total Tuition is: " + tuition);
// If-elseif-else statements based on scholar variable
}
}
How do I fix this error message?
More Info
I recently came across a question that was badly executed. Bad title, bad code, bad question (actually not question, but it could be assumed after some thought). It was from a new SO user.
I wanted to help out and looked at the code for a while. So I edited the post; fixed the code layout, simplified the code, ask the question the OP wanted to ask, etc.... That question is now above; however, the question was put on hold, and I read that questions can take a long time to get off of On Hold. You need something like 5 votes to reopen after it is put on hold. Something I don't see that will happen given that it has been a while since the question was first asked.
I had the answer complete and don't want to waste a good answer
OK, lets look at how to find the issue first!
(3) run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
(2) at java.lang.Integer.parseInt(Integer.java:497)
(1) at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Look at...
(1), here you can see in Main.java you have an issue on line 26
(2), here you can see more information on the issue. In fact you know you have an issue with Integer.parseInt.
You Don't have to worry about looking at this code, because you don't have a class called Integer with method parseInt in the package java.lang
You just know there is an issue here, and it deals with Integer.parseInt which you do call in your Main.java code!
So we located a possible area to check for the error!
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
(3), here we can see that a NumberFormatException was throw because you gave it (the Integer.parseInt that is) an input of "" (an empty string)
So How do you fix it?
First, you have to look at the input of Integer.parseInt
You can see you pass in tuition1 and scholar1
Look to see where those 2 variable are changed / created.
You can see the last thing you did was create those two variables and assigned them the empty string ("")
There is the problem!!
So you need to assign them a value from the user. That will be done via the showInputDialog(...).
the showInputDialog(...) returns a value that you can use! See here!
All you have to do is...
tuition1 = JOptionPane.showInputDialog("Input Your Tuition");
scholar1 = JOptionPane.showInputDialog("Choose A Scholar Discount: 1... 2... 3... 4...")
Take note that tuition1 and scholar1 should NOT be placed inside of the dialog box when you want to assign them values from the user. You need to have the user input some text into the dialog box, and that value will be returned when you press the OK button. So you have to assign that return value to tuition1 and scholar1
You are getting this exception because user is free to enter an input which is not a number. Integer.parseInt(String s) will throw a NumberFormatException if the argument passed to this method is not a valid number. You can restrict the user to input only numbers by the use of regular expressions. The code is below:
String tuition1="";
int tuition = 0;
boolean numFound =false;
try{
while(!numFound){
tuition1 = JOptionPane.showInputDialog("Input Your Tuition:");
Pattern p = Pattern.compile("[A-Z,a-z,&%$##!()*^]");
Matcher m = p.matcher(tuition1);
if (m.find()) {
JOptionPane.showMessageDialog(null, "Please enter only numbers");
}
else{
tuition = Integer.parseInt(tuition1);
numFound = true;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
This will show a message to user "Please enter only numbers", if he tries to enter something that cannot be converted to integer.

Checking whether the text in a JTextField is a certain data type

I am trying to write some validation code in my class for my GUI. How would I go about getting the text from a JTextField into a while statement and prompting a JOptionPane for the user to enter the necessary number(double)? To be more specific, how do I check if what I got from the JTextField is a string/string+number/anything other than a number?
String text=JTextField.getText();
while(text.equals*a string or anything but a number*);
JOP("Invalid input ............ etc...
If you have time, here is my GUI and my class. I am trying to do this for the rest of the methods. But the answer to the above will suffice.
http://www.mediafire.com/?f079i1xtihypg1b
http://www.mediafire.com/file/f079i1xtihypg1b/FinanceGUI.java
Update:
This is what I have so far:
//get the text entered in the amountRentText
//JTextField and parse it to a Double
String amtRentIn=amountRentText.getText();
try{Double.parseDouble(amtRentIn);}
catch(NumberFormatException nfe){
while()
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
double rent= Double.parseDouble(amtRentIn);
fin.setRent(rent);
What do I put in the while?
String amtRentIn=amountRentText.getText();
boolean incorrect = true;
while(incorrect){
try{Double.parseDouble(amtRentIn);incorrect = false;}
catch(NumberFormatException nfe){
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
}
javax.swing.InputVerifier is designed for this. Your implementation of verify() could invoke parseDuble(). Here's another example.
A "cheap" not too beautiful solution that occurs to me would be using the Double.parseDouble(..) on that string, and being ready to catch the parsing exception that would occur in the event the String had any non-numeric content.

Categories