Java, string to accept only letters and "if" statement - java

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/

Related

How to ask user for ONLY one word string input and produce error prompt in a try-catch block

EDIT: I figured it out! I got rid of the try-catch block because it just didn't work the way I wanted it to. The code below is my final one. Thank you to everyone who responded to this question.
I am trying to code a to-do list program. One function of this program is to search for the entries inside the string array. The user should only input a ONE WORD keyword so if the user inputs more than one word or none, a prompt should show telling the user to try again. The code I've written so far is inside a try-catch statement. Using next() scanner only takes the first word and disregards the rest when inputting a multiple-word keyword, instead of producing an Exception. Here is my code for it:
case 2:
String searchKeyword;
int success = 0;
while(success==0) {
System.out.print(">> Enter 1 keyword: ");
searchKeyword = sc.nextLine();
String splitSearchKeyword[] = searchKeyword.split(" ");
if (splitSearchKeyword.length == 1) {
if(Quinones_Exer2.searchToDoList(searchKeyword, todoList)==-1) {
System.out.println(">> No item found with that keyword!");
System.out.println();
}
else {
System.out.println(">> Found one item!");
System.out.println("("+(Quinones_Exer2.searchToDoList(searchKeyword, todoList)+1)+")"+" "+todoList[Quinones_Exer2.searchToDoList(searchKeyword, todoList)]);
System.out.println();
}
success++;
}
else {
System.out.println(">> Please input a single word keyword!");
System.out.println();
}
}
break;
}```
Use Scanner.nextLine() then split the supplied string. If the length of array is greater than 1 or the supplied string is empty then issue an invalid entry message and have the User enter the string over again:
while(tries2 == 0) {
searchKeyword = "";
while (searchKeyword.isEmpty()) {
System.out.println("Enter 1 keyword: ");
searchKeyword = sc.nextLine().trim();
if (searchKeyword.isEmpty() || searchKeyword.split("\\s+").length > 1) {
System.out.println("Invalid Entry! {" + searchKeyword
+ "You must supply a single Key Word!");
searchKeyword = "";
}
}
tries2++;
// ... The rest of your code ...
}
From the docs of Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
You would need to call next() again to get the the rest of the input.
Much simpler would be to use Scanner.nextLine() to get entire line and then use String.split() with whatever delimiter you are using to get an array of all inputted keywords.
Edit: Scanner.next(pattern) may do what you are looking for. It throws InputMismatchException if the input does not match provided pattern(regex). Example:
scanner.next("^[a-zA-Z]+$")
This requires the entire line to consist of lower and/or upper case letters and nothing else.

How to only allow the user to enter an input of a-z and using an if statement to prompt the correct input

I need to only allow a user to enter a character from the a-z range. I was thinking of using an if statement but its not working out for me.
System.out.println("Please enter letters of the alphabet");
String input1 = scnObj.nextLine();
if (input1 != a-z) {
System.out.println("Please try again.");
}
else
{
System.out.println("Correct.");
}
You can use regexp. Your case is simple and something like this:
if(!Pattern.compile("[a-z]*").matcher(line).matches()){
System.out.println("Please try again.");
}
If you want include also Uppercase, modfy if condition like this:
if(!Pattern.compile("[a-zA-Z]*").matcher(line).matches()){
System.out.println("Please try again.");
}
If space are allowed:
if(!Pattern.compile("[a-zA-Z\\s]*").matcher(line).matches()){
System.out.println("Please try again.");
}
In any case and for more complex cases please read the java doc
You could use a regular expression, but a simpler solution might be to take advantage of the fact that the characters in a - z are a in a linear progression within the character set tables and do something like...
String input1 = scnObj.nextLine();
if (!input1.trim().isEmpty()) {
char inputChar = input1.charAt(0);
if (inputChar >= 'a' && inputChar <= 'z') {
// Everything is good
} else {
// Everything is bad
}
}
This sounds like the perfect time for a regex implementation. If you have never heard regex I recommend checking out this video. Essentially it is used to match patterns within a string. For java you could simply check whether each character is a lower case letter with:
System.out.println("Please enter letters of the alphabet");
String input1 = scnObj.nextLine();
if (!input1.matches("[a-z]*") {
System.out.println("Please try again.");
} else {
System.out.println("Correct.");
}
However it might have to add a little more if you want to allow for spaces/hyphens. Good luck!

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{}

Do while loop error message

I am a beginner programmer (first post here!) and I cannot figure out how to create an error message with a "do while" loop. If given input that's not in the alphabet it is supposed to display the error message until given an input with only letters and then move on the to rest of the program. My code seems to loop forever even if given correct input. Any suggestions are greatly appreciated! :)
do {
input = JOptionPane.showInputDialog("What is your name?");
if (input.contains("[a-zA-Z]"))
name = input;
else
System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case");
} while (!input.contains("[a-zA-Z]"));
You can show user an error popup so he knows something is wrong with his/her input.
In else statement where you are Printing message just do
JOptionPane.showMessageDialog(frame,
"Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case.",
"Input error",
JOptionPane.ERROR_MESSAGE);
return;
For more information
You use the wrong method to validate your regex. .contains() expects a char sequence. That is not what you want.
You should instead use the .matches() method.
String input = "";
do{
input = JOptionPane.showInputDialog("What is your name?");
if (input.matches("[a-zA-Z]+")) // Replacing the contains()
name = input;
else
System.out.println
("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case");
}while (!input.matches("[a-zA-Z]+")); //Once again replacing contains()
input.contains("[a-zA-Z]") checks if input contains the text [a-zA-Z].
You can use the matches method.
input.matches("[a-zA-z]+")
Also, you should use [a-zA-z]+ as the pattern, since you are trying to match one or more alphabets.
The problem is related to how you check for the given input.
String input;
String name = "";
do {
input = JOptionPane.showInputDialog("What is your name?");
if (input.matches("[a-zA-Z]+")) {
name = input;
} else {
System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case");
}
} while (!input.matches("[a-zA-Z]+"));
using the matches function of string can help you achieve what you want
String.contains() method matches a set of character sequence.
What you've specified is a regular expression, hence, you should be using String.matches() or the Pattern class to perform the check.
It should be something like this using the Pattern class.
Pattern p = Pattern.compile("[a-zA-Z]+");
Matcher m = p.matcher(input);
if(m.matches){
//Do something
}
Refer to this documentation for more details

I want to know how to find a special character in a string

I am programming in Java in Eclipse, I want to ask users to enter their specific ID, Which starts with an uppercase G and has 8 digit numbers. like G34466567. if the user enters an invalid ID it will be an error. how can i separate a valid ID from others?
You can use regex. This pattern checks if the first character is a capital G and there are 8 digits following:
([G]{1})([0-9]{8})$
As you see there are two expressions which are separated by the (). The first says "only one character and this one has to be a capital G". And the second one says, there have to be 8 digits following and the digits can be from 0 to 9.
Every condition contains two "parts". The first with the [] defines which chars are allowed. The pattern inside the {} show how many times. The $ says that the max length is 9 and that there can't be more chars.
So you can read a condition like that:
([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
One condition
And in Java you use it like that:
String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);
As you see that matches method takes two parameters. The first parameter is a regex and the second parameter is the string to check. If the string matches the pattern, it returns true.
Create an ArrayList. Ask the user to input the ID, check if it is already there in the list, ignore, otherwise add that ID to the list.
EDIT: For ensuring that the rest 8 characters of the String ID are digits, you can use the regex "\\d+". \d is for digits and + is for one or more digits.
Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
System.out.println("Pleaes enter you ID.");
ID = sc.next();
if (IDS.contains(ID)) {
System.out.println("This ID is already added.");
} else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
IDS.add(ID);
System.out.println("Added");
} else {
System.out.println("Invalid ID");
}
System.out.println("Do you want to add more? y/n");
more = sc.next().charAt(0);
}
Assuming that you save the id as a string, you can check the first letter and then check if the rest is a number.
Ex.
String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9); //this will give you the number
To check that number is a number you could do the following instead of checking every character:
try {
foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
// this is not a number
}

Categories

Resources