I'm trying to make sure that the first character the user enters in this textbox is a letter. If it isn't, however, there will be a message box pop-up notifying the user that the first character cannot be a number, and must be a number. The problem is that the program completely ignores the code after the event occurs to check and see if there is a letter in the first position.
if (event.getSource() == item2)
{
string = String.format("Account number: %s", event.getActionCommand());
str = string.substring(1);
try{
Integer.parseInt(string.substring(0,1));
parsable = true;
}catch(NumberFormatException e){
parsable = false;
}
if(parsable == true)
{
JOptionPane.showMessageDialog(null, "ENTER THE LETTER CORRESPONDING WITH YOUR ACCOUNT NUMBER AS THE FIRST CHARACTER IN THE TEXT FIELD.");
}
/*
try
{
Integer.parseInt(str);
}
catch(NumberFormatException e)
{
String.format("enter a valid number");
}
*/
}
Any help is appreciated.
because you are using String.format("Account.... your string's first character will always be 'A' of Account you have to check on String which you recived from event.getActionCommand() mathod
Related
This is the code I have in a setName() method which I want to only accept letters (not digits)
playerName = "";
if (playerName.isDigit)
{System.out.println("Please enter letters only");
}
I am getting an error message which says "illegal parenthesised expression.
String type doesn't have isDigit property. Use the following code to check if your variable contains digits.
if (playerName.matches(".*\\d+.*")) {
System.out.println("Please enter letters only");
}
This code will work for you :
public static void setName ( String playerName ){
if (playerName.matches(".*\\d.*") || playerName.isEmpty()) {
System.out.println("Please enter letters only");
} else {
//Your code here
}
}
You can use Lambda expression to check whether the input string contains only character or not. In your setName() method, do the following
playerName="abcd"; //Take playerName from user input or as method argument
if(playerName==null || playerName.equals("") || !playerName.chars().allMatch(Character::isLetter))
System.out.println("Please enter letters only");
else{
//Do your work if someone enters name containing only letters.
}
There's no isDigit method in String.class in Java, but there're lots of ways to do it.
Take a look: https://mkyong.com/java/java-how-to-check-if-a-string-is-numeric/
I am creating a program that is a simple mock-up of a banking account system. I have a simple method that when called asks the user to input a name (String) and a starting account balance (double) and creates a new Person object / Account object.
This method is called via a menu that uses 1-9 (int) options, and say '1' is pressed to create a new account. So the code (before accepting the string) has a default input.nextLine(); command to catch the int input before capturing the actual name input (customerName = input.nextLine();).
The issue I am having is that I am trying to add exception handling to this method to ensure that the name String input is only letters and spaces. When running the first time and someone puts an incorrect input, it would re-output the "Please input a name" but then they would have to enter the name twice since the input.nextLine(); was still in there (but not catching a menu input). So I added a if/else decision structure with a counter for the first time that the program runs if the (counter == 0) then it keeps the input.nextLine() and increments the counter, but if the (counter > 0) it gets rid of the input.nextLine() so that the program runs fine.
This causes another problem, that if the user tries to create multiple accounts, it will cause the program to stop printing the input.nextLine() the second time it is called and automatically assume the menu option input is what the name is supposed to be, and sends an error. Is there a better way to get this working the way I intended?
Sorry if the description isn't very clear, it's a hard problem to describe.
Here's the code:
public void menuOptionOne() {
do {
try {
if (counter == 0) { // counter is initially set to 0
System.out.println("Please input the customer's name: ");
input.nextLine(); // catches the menu input
customerName = input.nextLine();
matcher = pattern.matcher(customerName);
counter++; // increments the counter in case the user's input is invalid
if (!matcher.find()) { // if it has non-letter/space characters present, throws exception
throw new Exception("Try again. (Incorrect input: name must contain only letters)");
}
} else if (counter > 0) { // asks the user to input name again, without the input.nextLine() which is intended to catch the menu int input
System.out.println("Please input the customer's name: ");
customerName = input.nextLine();
matcher = pattern.matcher(customerName); // checks the input to ensure it is only letters and/or spaces
if (!matcher.find()) {
throw new Exception("Try again. (Incorrect input: name must contain only letters)");
}
}
continueInput = false;
} catch (Exception ex) {
System.out.println(ex.toString());
}
} while (continueInput);
So when this gets called twice in a row, it automatically goes to the second decision structure, without the input.nextLine(), and that catches the menu input (1) and throws the exception. How can I get it to work properly each time the method is called?
This is the output when it is called twice in a row (note: it saves the menu input as the new customer name, even though it is a number):
Please input the customer's name:
java.lang.Exception: Try again. (Incorrect input: name must contain only letters)
Please enter the new balance:
You want to do two things in the input retrieval:
allow a series of inputs by reusing this method.
check the content of the input and start again if not suitable.
The way you are using to "allow a series of inputs by reusing this method" is the source of your error.
In a general way you should favor the use of the most restricted scope when it is enough.
By declaring continueInput and counter as a field variable instead of a local variable you create a coupling between invocations of menuOptionOne().
Which explain your problem :
This causes another problem, that if the user tries to create multiple
accounts, it will cause the program to stop printing the
input.nextLine() the second time it is called and automatically assume
the menu option input is what the name is supposed to be, and sends an
error. Is there a better way to get this working the way I intended?
This code should be enough :
public void menuOptionOne() {
// change
int counter = 0;
boolean continueInput = true;
// end change
do {
try {
if (counter == 0) { // counter is initially set to 0
System.out.println("Please input the customer's name: ");
input.nextLine(); // catches the menu input
customerName = input.nextLine();
matcher = pattern.matcher(customerName);
counter++; // increments the counter in case the user's
// input is invalid
if (!matcher.find()) { // if it has non-letter/space
// characters present, throws
// exception
throw new Exception("Try again. (Incorrect input: name must contain only letters)");
}
} else if (counter > 0) { // asks the user to input name again,
// without the input.nextLine()
// which is intended to catch the
// menu int input
System.out.println("Please input the customer's name: ");
customerName = input.nextLine();
matcher = pattern.matcher(customerName); // checks the input
// to ensure it
// is only
// letters
// and/or spaces
if (!matcher.find()) {
throw new Exception("Try again. (Incorrect input: name must contain only letters)");
}
}
continueInput = false;
} catch (Exception ex) {
System.out.println(ex.toString());
}
} while (continueInput);
}
The way you are using to "check the content of the input and start again if not suitable", works but you could do much more simple and avoid repeat yourself.
Ah, I figured out my issue.
I set the variable counter = 0; at the top of my method and then at the bottom set continueInput = true; again
Now it works as intended.
So working code looks like:
public void menuOptionOne() {
counter = 0; // set counter to 0
do {
try {
if (counter == 0) {
System.out.println("Please input the customer's name: ");
input.nextLine();
customerName = input.nextLine();
matcher = pattern.matcher(customerName);
if (!matcher.find()) {
counter++;
throw new Exception("Try again. (Incorrect input: name must contain only letters)");
}
} else if (counter > 0) {
System.out.println("Please input the customer's name: ");
customerName = input.nextLine();
matcher = pattern.matcher(customerName);
if (!matcher.find()) {
throw new Exception("Try again. (Incorrect input: name must contain only letters)");
}
}
continueInput = false;
} catch (Exception ex) {
System.out.println(ex.toString());
}
} while (continueInput);
continueInput = true; // reset the continue input value
The prompt is to have a user input a password and the password must be at least 8 characters with no white spaces, must have one upper case letter, and must have one digit. It has to use a while loop. If the password conforms it should output "password ok" or otherwise say "try again"
Anyone know what to do for this?
All I can pretty much do is the scanner and user input
Use 2 boolean flags. One each for checking presence of digit, uppercase letter. Your condition could go like :
//loop start
{
if(string.charAt(i)==space){
print "not valid"
return false;
}
// check for capital letter here and set flag to true if it is found.
// check digit here and set that flag to true if found.
}//loop end
// outside the loop make these checks
if(string.length>8 && isCapitalFound && isDigitFound)
//print "valid"
return true
I made your home work for you:
boolean noWhite = false;
boolean oneUppercase = false;
boolean oneDigit = false;
Scanner scan = new Scanner(System.in);
String pass = "";
while (!noWhite || !oneUppercase || !oneDigit || pass.length() < 8) {
System.out.print("new pass: ");
pass = scan.next();
noWhite = !pass.contains(" ");
oneUppercase = !pass.equals(pass.toLowerCase());
oneDigit = pass.matches(".*\\d.*");
}
System.out.println("OK");
So let's imagine we have this loop that obtains input from the user in the form of strings. With that input, what we want to do is set up a set of validations that will check if certain criteria are met. If all of these conditions are met, it'll complete the action in question. However; if it doesn't, it'll tell them the error and restart the process.
My question is about validating the existance (or non-existance) of a letter in a string. I have this program and for one of these validations, I need to check the entire string. If the string does not have at least one character that isn't a letter, I want to halt the action and explain that a non-letter character is required.
The problem is that I am not sure how I could replicate this in an expression in an if loop. Here's what I have so far.
public static changePassword() // Method that runs through the process of changing the password.
{
// Retrieving the current and new password from the user input.
System.out.println("Welcome to the change password screen.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your current password: ");
String currentPassword = keyboard.nextLine();
System.out.print("Please enter the new password: ");
String newPassword1 = keyboard.nextLine();
System.out.print("Please enter the new password again: ");
String newPassword2 = keyboard.nextLine();
// Validating the new password entry.
if (newPassword1.equals(newPassword2)) // Checking to see if the new password was entered exactly the same twice.
{
if (newPassword1.length() >= 6) // Checking to see if the new password has 6 or more characters.
{
if (**some expression**) // Checking to see if the password has at least one non-letter character.
{
currentPassword = newPassword1 // If all conditions are met, it sets the current password to the password entered by the user.
}
else // If there isn't a non-letter character, it informs the user and restarts the process.
{
System.out.println("The new password must have a non-letter character.");
changePassword();
}
}
else // If there is less than 6 characters, it informs the user and restarts the process.
{
System.out.println("The new password can not be less than 6 characters.");
changePassword();
}
}
else // If the new passwords don't match, it informs the user and restarts the process.
{
System.outprintln("The passwords must match.");
changePassword();
}
}
Assuming by "letter" you mean an english character in A-Z, a-z, just iterate through the string and return true if you encounter a character whose int value is outside the letter range.
public static boolean containsNonLetter(String s){
for(int i = 0; i < s.length(); i++){
int ind = (int)s.charAt(i);
if(ind < 65 || (ind > 90 && ind < 97) || ind > 122)
return true;
}
return false;
}
I am making the assumption that by letter you meant alphabets. If you use regex pattern you can have a very clean code as well you have ability to update the pattern as necessary. To learn more check Java Pattern. Here is the code.
private static final Pattern APLHA = Pattern.compile("\\p{Alpha}");
public static boolean hasLetter(String input) {
return APLHA.matcher(input).find();
}
I have a loop which breaks upon receiving the correct input from the console. I am using Scanner to read in a String from System.in, which seems to be what's giving me trouble. Here is my code:
boolean loop = true;
while(loop) {
try {
System.out.println("Enter an input (\"input a\" or \"input b\"): ");
String input = scanner.nextLine();
System.out.println("");
if (input.equals("input a")) {
System.out.println("Answer to input a.");
} else if (input.equals("input b")) {
System.out.println("Answer to input b.");
} else {
throw new IllegalArgumentException();
}
loop = false;
} catch (InputMismatchException e) {
System.out.println(e.getMessage());
System.out.println("");
} catch (IllegalArgumentException e) {
System.out.println("Input not recognized. Please enter a valid input.");
System.out.println("");
}
}
When this is called, it loops once without even waiting for input from the user, then actually stops and does what it is supposed to the second time around. IE, the output for this, without the user giving any input at all, is:
Enter an input ("input a" or "input b"):
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"):
If I give it a bad input (so that it loops and asks again), it does the same thing where it loops twice before waiting. I have no idea why.
Why is this happening, and what should I do to avoid it?
EDIT: Test scenarios after hasNext check:
Scenario A:
Enter an input ("input a" or "input b"): input a //my input
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"): //no input given here
Answer to input a.
Scenario B:
Enter an input ("input a" or "input b"): ddd //my input
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"): //no input given here
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"): input b //my input
Answer to input b.
The code which produces this:
boolean loop = true;
while(loop) {
if (scanner.hasNext()) {
try {
System.out.println("Enter an input (\"input a\" or \"input b\"): ");
String input = scanner.nextLine();
System.out.println("");
if (input.equals("input a")) {
System.out.println("Answer to input a.");
} else if (input.equals("input b")) {
System.out.println("Answer to input b.");
} else {
throw new IllegalArgumentException();
}
loop = false;
} catch (InputMismatchException e) {
System.out.println(e.getMessage());
System.out.println("");
} catch (IllegalArgumentException e) {
System.out.println("Input not recognized. Please enter a valid input.");
System.out.println("");
}
}
}
I tried out the code you've wrote down in your question, as a single question, but I can't find any problem with it at all. However, I think I know just the answer.
If you did any other input before this with primitive types or just next(), you need to flush the newline character that unfortunately those next methods leave behind. To do this, just call "scanner.nextLine()" before the statement where the method returns the inputted string and assigns it to input.
You want to make sure that you call in the method as separate; you know, on its own. It's best if you put it in your while loop at the top before you enter so that way for every iteration, the newline character is cleared. The statement will then get rid of the newline character and thus the input buffer is empty. Once that's cleared out, you can finally input your string at your first loop iteration.
How's that for an answer? Try it out and let me know if it works!
You should first check if the user has enetered any data :
if(scanner.hasNext())
{
// code logic
}