Using ParseInt() with JTextField.getText() throwing errors - java

I am currently trying to receive an input from a JTextField and store it as an integer in my data. When I use ParseInt(), an error message pops up
Invalid SSN
but when I hardcode my variable SSN with the same text I enter to the JTextField, it works.
Here's the specific section:
try {
ssn = Integer.parseInt(ssnText.getText());
//ssn = 123456789;
if((Integer.toString(ssn).length()) != 9)
{
JOptionPane.showMessageDialog(null,"Invalid SSN","Invalid SSN", JOptionPane.ERROR_MESSAGE);
ssnText.setText("");
return;
}
}

Related

How to check the user input is an integer or not with Scanner?

I want the country codes are integer that input by the user. I want an error message to be show when user inputs a code which is not an integer. How can I do this? The program is to ask user to enter country name and country code. In which user will input the country code. But if user inputs a character I want a message to be shown saying Invalid Input.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
If the input is not an int value, then Scanner's nextInt() (look here for API) method throws InputMismatchException, which you can catch and then ask the user to re-enter the 'country code' again as shown below:
Scanner in = new Scanner(System.in);
boolean isNumeric = false;//This will be set to true when numeric val entered
while(!isNumeric)
try {
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
isNumeric = true;//numeric value entered, so break the while loop
System.out.println("codeNumber ::"+codeNumber);
} catch(InputMismatchException ime) {
//Display Error message
System.out.println("Invalid character found,
Please enter numeric values only !!");
in.nextLine();//Advance the scanner
}
One simple way of doing it, is reading a line for the numbers as you did with the name, and then checking witha Regex (Regular Expression) to see if contains only numbers, with the matches method of string, codeNumber.matches("\\d+"), it returns a boolean if is false, then it's not a number and you can print your error message.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
String codeNumber = in.nextLine();
if (codeNumber.matches("\\d+")){
// is a number
} else {
System.out.println("Please, inform only numbers");
}
You can do something like this, by first getting the input as a string, then try to convert the string to an integer, then outputs an error message if it can't:
String code= in.nextLine();
try
{
// the String to int conversion happens here
int codeNumber = Integer.parseInt(code);
}
catch (NumberFormatException nfe)
{
System.out.println("Invalid Input. NumberFormatException: " + nfe.getMessage());
}
You could instead check hasNextInt then call nextInt
int codeNumber;
System.out.println("Enter country code:");
if(in.hasNextInt())
{
codeNumber = in.nextInt();
}
else
{
System.out.println("Invalid Code !!");
}
If you are creating your own custom exception class, then use regex to check if the input string is an integer or not.
private final String regex = "[0-9]";
Then, check if the input follows the regex pattern.
if (codeNumber.matches(regex)) {
// do stuff.
} else {
throw new InputMismatchException(codeNumber);
}
You can use build in InputMismatchException if you are not creating your custom exception handler.

ChangePassword method in Java

I'm working on a Java project, building a simple system, and it has some methods, one of them is "Change PassWord", I put the user's information (username & password) in a text file called ("Users.txt").
Now this is the description of the method:
boolean ChangePassWord(): Asks the user to enter old password for
verification, the user has at maximum three tries to enter correct old
password; if not the password will not be changed and a message Box
will be shown for the user. If user entered correct old password then
he is authenticated to changer his password and asked to enter new
password and confirming the new. Once if confirmed correctly the old
password will be changed to the new one and a message box will be
shown if wrong confirmation the old password will not be changed and a
message box will be shown.
I wrote this code:
boolean changePassword(){
String pass=JOptionPane.showInputDialog(null, "Enter old password: ", "Input", JOptionPane.QUESTION_MESSAGE);
if(pass.equals(Password)) {
String newpass=JOptionPane.showInputDialog(null,
"Enter new password: ", "Input", JOptionPane.QUESTION_MESSAGE);
String connewpass=JOptionPane.showInputDialog(null,
"Enter confirming new password: ", "Input",
JOptionPane.QUESTION_MESSAGE);
if(newpass.equals(connewpass)){
Password= newpass;
JOptionPane.showMessageDialog(null, "password changed ", "message",
JOptionPane.INFORMATION_MESSAGE);
return true;
}
else
JOptionPane.showMessageDialog(null, "Wrong Conferm ", "message",
JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "Wrong password ", "message",
JOptionPane.INFORMATION_MESSAGE);
return false;
}
but I think that it's wrong, and I need to use a loop I think.
I hope you help me!
A while loop is appropriate for your case. I will briefly explain how this while loop runs 3 times.
So, first n=3. The condition n-- > 0 means 2 things. Check if n is greater than zero and subtract the value of n by 1. These 2 things happen in that exact order.
So the condition checks that n is indeed greater than zero and enters the loop. At the same time n is also decreased by 1 and becomes 3-1=2.
This goes on 3 times. After the 3rd time, n becomes 0. And the condition 0 > 0 is false and therefore the while loop breaks.
boolean changePassword(){
String pass = ""; //get old password from user
int n = 3;
while (n-- > 0) {
if(pass.equals(Password)) {
String newPass = ""; // get new password from user
String conNewPass = ""; // confirm new password from user
if (newPass.equals(conNewPass)) {
Password = newPass;
// password changed
return true;
} else {
// wrong confirmation.. password not changed
return false;
}
}
else {
// tell user to enter the correct old password
pass = ""; // ask user for old password again
}
}
// show error message that user entered the old password 3 times incorrectly
// and return false
return false;
}

JOptionaPane Inputdialogbox and buttons

The below code is working perfecly
String input = JOptionPane.showInputDialog(null, "Enter Input",
"Dialog title",JOptionPane.QUESTION_MESSAGE);
Now I have Ok and Cancel buttons. I want to do something like
if(OK is selected){
String input1 = input
do something with input1
}
else if (cancel is selected){
System.dispose();
}
I'm clueless about what to write inside if condition. I know that for ShowOptionDialog I can get an int of selected option and use it but for inputdialog Im not sure how I can get both the selected option and input text.
Could you please help me
So the JavaDocs say
Returns:
user's input, or null meaning the user canceled the input
That mean that something like
String input = JOptionPane.showInputDialog(null, "Enter Input",
"Dialog title",JOptionPane.QUESTION_MESSAGE);
if (input != null) {
// User accepted
} else {
// User cancelled
}
Should work...

Cancel button in showinputdialogbox

I have a few buttons on my panel and everytime I click on it an input dialog box appears. It has an inbuilt cancel button. Now, when i click on the cancel button in the beginning of the code without entering the quantity in the dialog box, it says, "This is an invalid" number. This line has to only appear if the user enters alphabets or symbols, and not on pressing cancel. Can we solve this?
First you need a way to decide if a String represents a number; the method below uses Double.valueOf() to decide.
private Double valueOf(String s) {
try {
return Double.valueOf(s);
} catch (NumberFormatException e) {
return null;
}
}
Here's an example of how you might use the method:
private void display() {
String input = JOptionPane.showInputDialog(
null, "Enter a number?", "Number", JOptionPane.QUESTION_MESSAGE);
Double value = valueOf(input);
JOptionPane.showMessageDialog(null, "The value " + input
+ " is " + (value != null ? "valid" : "invalid") + ".");
}
See also How to Make Dialogs.
Try doing,
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if (Input.equals(""))
{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}
The following link explains it even better: Simple Data Validation.
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if
(Input.matches(("((-|\+)?[0-9]+(\.[0-9]+)?)+"))) {
JOptionPane.showMessageDialog(null,"valid number");
}
else{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}

When I press the Search button leaving the user input field blank, I get java.lang.NumberFormatException

When I press the Search button leaving the user input field blank, I get the following error page:
java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
java.lang.Integer.parseInt(Integer.java:470)
java.lang.Integer.parseInt(Integer.java:499)
Code that throws the error is int nstudentid = Integer.parseInt(studentid);
You are trying to parse a number from a string that is empty, you should add a check:
//this means the number is not empty
if(studentid != null && !studentid.equals("")){
int studentIdNum = Integer.parseInt(studentid);
}
else{
//no number, deal with it
throw new Exception("Invalid student Id!");
}

Categories