How to validate a Long.parselong passwd try catch - java

here is my situation. I have a project that I am doing. I'm using netbeans 8.0.2 IDE java language. Here is my code:
try{
memdt = request.getParameter("member date");
if(!memdt.isEmpty()){
n.setMemdt(memdt);
}else{
msg += "Member date field is empty<br>";
}
} catch (Exception e){
msg += "Member date error: " + e.getMessage() + "<br>";
}
That code is fine but what I want to do now is validate using the try catch method for password and that is a long character. Does anyone know how to do that? Thank you.

Judging by the title of your question, you are trying to do something like this:
try {
Long.parseLong(memdt);
} catch(NumberFormatException nfe) {
msg += "Member date error: not a number";
}
NumberFormatException it's what the Number classes generally throw when a string can not be parsed. The result of Long.parseLong() is discarded since the long value it returns is irrelevant, the test just checks that the parsing can be done.

Related

I am getting the error message java.lang.NumberFormatException: For input string: "" and I am not sure why and how to fix it

I am pretty new to Java and I am doing this project. I keep getting the following error message while I click a jButton (submitButton) in the runtime, and I am not sure why as it is not telling which line the problem is at.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Below is my code, I was wondering if anybody could help? Maybe help me find the error, or tell me what the error message means. Thank you!
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fullName = nameText.getText();
String email = emailText.getText();
String address = addressText.getText();
String phoneNumber = phoneText.getText();
// sets either true or false to membershipSelected if a plan is selected
boolean membershipSelected = standardMembership.isSelected() || silverMembership.isSelected() || goldMembership.isSelected();
double total = 0;
// checks if the text entered in phone number text field can be parsed to an integer
// this is only possible if it is a number, if it is a string, then error pop-up appears
try {
int phone = Integer.parseInt(phoneText.getText());
}
catch(Exception e) {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid phone number, please try again!");
}
// checks if email text field does not contain "#" or a domain
if(!email.contains("#") || !email.contains(".com") && !email.contains(".de") && !email.contains(".co.uk")){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid email address, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if length of phone number is 11, if not shows error pop-up
int phoneLength = Integer.parseInt(phoneText.getText());
if(phoneLength != 11){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This phone number is not long enough, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if a plan is selected, if not shows error pop-up
if(membershipSelected){
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
else {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "Please select a membership!");
}
// sets the final overview to an empty string that can be added to with selections later
String overview = "";
if (standardMembership.isSelected()){
overview = overview + " " + standardMembership.getText() + '\n';
total = 200;
}
if (silverMembership.isSelected()){
overview = overview + " " + silverMembership.getText() + '\n';
total = 450;
}
if (goldMembership.isSelected()){
overview = overview + " " + goldMembership.getText() + '\n';
total = 600;
}
}
You have two places where you perform Integer.parseInt(phoneText.getText());
At the first time, the parsing is surrounded by a try-catch block and that handles the NumberFormatException that would be thrown in case phoneText.getText() is empty or not a number.
The second time, the parsing is not surrounded by any try-catch. This time the NumberFormatException thrown is unhandled and hence you are seeing the Exception.
You should ideally parse the phoneText.getText() once and have your conditions modified accordingly.

Java add each value to a string

I have a really big program that needs to check what character is typed this is just a part of the broken part. So it worked when I had it logging each character typed. But when I try to add each character to the string so when they type the word hi it looks like this:
hi
and NOT
h
i
No matter what i try it either gives me the first value typed and doesnt add each character to the string I also want it to print out the string every 5 seconds im not sure if I did that right either but it might be correct.
String log = " ";
if(event.getVirtualKeyCode() == GlobalKeyEvent.VK_SPACE){
log = log + "";
}
if(event.getVirtualKeyCode() == GlobalKeyEvent.VK_BACK){
log = log + "[BACKSPACE]";
}
String timestamp = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(Calendar.getInstance().getTime());
while(true){
try {
Thread.sleep(5000);
System.out.println("[" + timestamp + "]" + log);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
Try to declare a new string:
String log = new String(" ");

Checking if a given String is a valid currency using number format

I have below strings:
String str1 = "$123.00";
String str2 = "$(123.05)";
String str3 = "incorrectString";
I want to check and output like:
if(str1 is a valid currency){
System.out.println("Str1 Valid");
}else{
System.out.println("Str1 InValid");
}
if(str2 is a valid currency){
System.out.println("Str2 Valid");
}else{
System.out.println("Str2 InValid");
}
if(str3 is a valid currency){
System.out.println("Str3 Valid");
}else{
System.out.println("Str3 InValid");
}
UseCase: I am parsing a pdf using pdfbox. Given a searchterm say "abc", I want to read next token after the search term. For this purpose, I am searching for the search term in parsed pdf text and then reading the next token to that search term.
The token should be a valid currency. But there could be a case where in "abc" is present at two different places in a page with one having valid currency token next to it while the other not.
So I want to put in a check that if the token I am reading is not a valid currency token, break the loop and continue the search on the page.
I did it as below:
if (tokenRead.length() > 0) {
String temp = tokenRead.replace("$", "").replaceAll("\\(", "");
char checkFirstChar = temp.trim().charAt(0);
if (!(checkFirstChar >= '0' && checkFirstChar <= '9')) {
System.out.println("breaking");
break;
}
}
This works, but I believe there should be a elegant solution using NumberFormat.
Hence the question!
Thanks for reading!
NumberFormat has nothing out of the box for your use case.
A possible solution I could come up with is this:
Currency currency = Currency.getInstance(currentLocale);
String symbol = currency.getSymbol();
if(string.startsWith(symbol) || string.endsWith(symbol)){
System.out.println("valid");
}else{
System.out.println("invalid");
}
But then you still need to check if the rest of the string can be parsed to a number.
Therefore I recommend to have a look at Apache Commons Currency Validator, it may fit your needs:
#Test
public void test() {
BigDecimalValidator validator = CurrencyValidator.getInstance();
BigDecimal amount = validator.validate("$123.00", Locale.US);
assertNotNull(amount);
//remove the brackets since this is something unusual
String in = "$(123.00)".replaceAll("\\(", "").replace(')', ' ').trim();
amount = validator.validate(in, Locale.US);
assertNotNull(amount);
amount = validator.validate("invalid", Locale.US);
assertNull(amount);
}
You could try DecimalFormat. It allows you to handle positive and negative value patterns separately using ;:
List<String> list = new ArrayList<>();
list.add("$123.00");
list.add("$(123.05)");
list.add("incorrectString");
NumberFormat nf = new DecimalFormat("¤#.00;¤(#.00)", new DecimalFormatSymbols(Locale.US));
try {
for(String str : list){
nf.parse(str);
}
} catch (ParseException e) {
System.out.println(e.getMessage());
}

Try and catch not working JOptionPane(Java)

I have a JList and a string that is the JList's selection. If you click a JButton, It displays your JList selection. If you don't click a JList selection, It returns an error, So i used try catch, but it still returned an error.
here is my code, there are no errors in editor.:
#Override
public void actionPerformed(ActionEvent e) {
String choice = chooser.getSelectedValue().toString();
String companyname = name.getText();
try{
JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: " + companyname + "" +"</html>" );
}catch (Exception e1){
JOptionPane.showMessageDialog(frame, "Please fill in both inputs");
}
}
And also the try works fine if there's no error, but the catch just doesn't work. I also tried to catch NullPointerException and if ,else if choose = null, but it still didn't work. Not even the option pane pops up with null in its place.
Just where would expect an exception to occur?
try{
String choice = chooser.getSelectedValue().toString();
String companyname = name.getText();
JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: " + companyname + "" +"</html>" );
}catch (Exception e1){
JOptionPane.showMessageDialog(frame, "Please fill in both inputs");
}
MIGHT be a better solution, given the fact that JList#getSelectedValue will return null if nothing is selected...but then you would need to catch a NullPointerException or Throwable instead of Exception
Updated with example
Branching by exception is not a good way to design applications. Exceptions should be used to trap unexpected states. You would seem that you are expecting invalid results.
A better approach would be to actually inspect each of the values in turn and determine if they are valid.
Object value = chooser.getSelectedValue();
if (value != null && value instanceof String) {
String choice = chooser.getSelectedValue().toString();
String companyname = name.getText();
if (companyname != null && companyname.trim().length() > 0) {
JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: " + companyname + "" +"</html>" );
} else {
JOptionPane.showMessageDialog(frame, "The company name is invalid, please provide one");
}
} else {
JOptionPane.showMessageDialog(frame, "Your company type choice is invalid, please select one");
}
Im fairly sure showMessageDialog() doesn't throw any exceptions, if any probably just a null pointer. Maybe try an if-else.
EDIT Here is some code, this should work as a full replacement.
Code:
if(! choice == null){
if(!companyname.equals("");){
JOptionPane.showMessageDialog(frame, "<html> Welcome to your new Company!<br><br>Company type: "+ choice + " " + "<br>" + "Company Name:" + companyname + "" +"</html>");
}else{
JOptionPane.showMessageDialog(frame, "Please fill in the company name!");
}
}else{
JOptionPane.showMessageDialog(frame, "Plaease fill in choice!");
}
You are actually not guaranteed that the showing of the dialog will be done on the calling thread - if showMessageDialog() is invoked from a background thread, the UI will still be displayed on the event thread - the calling thread will just be blocked until it is closed.
If the UI does throw an exception, it will happen on a different thread and not propagate to your code (have a look at the source code to the AWT event queue to get an idea of the mechanics of this).

How do you include user input in exception message Java?

Is it possible, in Java, to include a user's input into an exception message while also using the valuse as an int or double? For example, they should enter a number (e.g., 5) but instead fat-finger something like (5r).
Is it possible to have a message say something like "You entered 5r, but should have entered a number."?
I tried using the traditional way of getting variables to print in Java here:
try {
System.out.println();
System.out.println("Value: ");
double value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
In this case, I am trying to get value displayed in the Exception message, where value is the user's invalid input.
At value it gives the error cannot find symbol.
Below is the answer I came up with. The reason I choose this answer was because most of your answers produced the output, "You entered 0.0 ..." because the answer must first be a string to be printed in the console. In addition, to be used as a number elsewhere in the program the String has cast to an Object of type Double or Integer :
String value = null; //declared variable outside of try/catch block and initialize.
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextLine(); //Accept String as most of you suggested
Double newVal = new Double(value); //convert the String to double for use elsewhere
exec.ds.push(newVal); //doulbe is getting used where it would be a 'number' instead of string
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number"); //the String valuse is received and printed as a String here, not a 'number'
} //now prints what the users inputs...
This does not work, because value is no longer in scope in the catch block. Instead you can declare it before the try:
double value = 0;
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
} catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
This will however not help if the exception is thrown because of a syntax error in the double. To handle this, you need to read a String and then convert to a double.
Get user input:
String input = '';
try{
Console console = System.console();
input = console.readLine("Enter input:");
}
... then in your catch you could do:
catch (Exception e1) {
System.out.println(e1+ "You entered: " + input + ": You must enter a number");
}
Other than the above, I don't see what the problem is. You can google how to get user input in Java, and then just take the input, put it in a variable, and print it out on error.
In this case - no, as the calling of sc.nextLine() causes the exception to be thrown, so no value is written to variable value.
Moreover, value is a local variable in this case and is unavailable from other blocks of code.
value it gives the error cannot find symbol.
You have declare the value in local block. And you are trying to access it outside the block.
Is it possible to have a message say something like "You entered 5r, but should have entered an number.
Better option is to use flag variable and loop until user enter correct number.
boolean flag = true;
double value = 0;
while(flag)
{
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextDouble();
exec.ds.push(value);
flag = false;
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
}
According to the documentation nextDouble():
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value.
So, if the input cannot be translated into a double, an exception is thrown. If you want to provide the inputted string in the exception message, I suggest you read the line as a string and try to parse it to a double, and if that fails, you can include the read line in the exception message.

Categories

Resources