How to find an invalid character or symbol inside a string - java

I'm creating a program that prints user details, first the user inputs their details and then the program correctly formats the details and prints them inside a formatted box. I want the program to read strings and see if the users have entered invalid characters. For example the code below requests for the users first name:
// this code below is used to find the largest string in my program, ignore if this wont interfere
String fname = scan.nextLine(); //main scan point.
//below is used to calculate largest string inputted by the user.
int input = 0;
int fnamelength1 = fname.length();
input = fnamelength1;
int longest = 0;
if(input > longest)
longest = input;
If at this point the user enters #~~NAME~~# as their name, the program currently allows that... I want to make the program read what the user has inputted and print a message if their input isn't correct for example contains invalid symbols.
EDIT:
I'm considering anything other than characters in the alphabet as invalid... any numbers or symbols would therefore be invalid.
VALID:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Also valid:
' - .

This can be done using regular expressions with the String.matches method. Here you define a pattern and if the string matches your pattern then it can be considered valid:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = fname.matches("[^a-zA-Z'-]]");
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
EDIT
With String.matches we can't make a global search of invalid characters (what we want in this case). So is better using Matcher.find for this:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
Pattern pattern = Pattern.compile("[^a-zA-Z'\\-\\s]");
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = pattern.matcher(fname).find();
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
This time the pattern will validate any invalid character anywhere in the string.

One approach would be to use regular expressions, along with the String.matches() method.
As an example:
String fname;
... some code to get fname ...
boolean valid = fname.matches("[a-zA-Z]+");
valid should be true if and only if fname is a String containing alphabetic characters, and not empty.
If empty strings are also valid, then:
boolean valid = fname.matches("[a-zA-Z]*");
Look up the Java class Pattern for other variations.

Related

How can I obtain the first character of a string that is given by a user input in java

I want the user to input a String, lets say his or her name. The name can be Jessica or Steve. I want the program to recognize the string but only output the first three letters. It can really be any number of letters I decide I want to output (in this case 3), and yes, I have tried
charAt();
However, I do not want to hard code a string in the program, I want a user input. So it throws me an error. The code below is what I have.
public static void main(String args[]){
Scanner Name = new Scanner(System.in);
System.out.print("Insert Name here ");
System.out.print(Name.nextLine());
System.out.println();
for(int i=0; i<=2; i++){
System.out.println(Name.next(i));
}
}
the error occurs at
System.out.println(Name.next(i)); it underlines the .next area and it gives me an error that states,
"The Method next(String) in the type Scanner is not applicable for arguments (int)"
Now I know my output is supposed to be a of a string type for every iteration it should be a int, such that 0 is the first index of the string 1 should be the second and 2 should be the third index, but its a char creating a string and I get confused.
System.out.println("Enter string");
Scanner name = new Scanner(System.in);
String str= name.next();
System.out.println("Enter number of chars to be displayed");
Scanner chars = new Scanner(System.in);
int a = chars.nextInt();
System.out.println(str.substring(0, Math.min(str.length(), a)));
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.
Instead, use code point integer numbers to work with individual characters.
Call String#codePoints to get an IntStream of the code point for each character.
Truncate the stream by calling limit while passing the number of characters you want.
Build a new String with resulting text by passing references to methods found on the StringBuilder class.
int limit = 3 ; // How many characters to pull from each name.
String output =
"Jessica"
.codePoints()
.limit( limit )
.collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
)
.toString()
;
Jes
When you take entry from a User it's always a good idea to validate the input to ensure it will meet the rules of your code so as not to initiate Exceptions (errors). If the entry by the User is found to be invalid then provide the opportunity for the User to enter a correct response, for example:
Scanner userInput = new Scanner(System.in);
String name = "";
// Prompt loop....
while (name.isEmpty()) {
System.out.print("Please enter Name here: --> ");
/* Get the name entry from User and trim the entry
of any possible leading or triling whitespaces. */
name = userInput.nextLine().trim();
/* Validate Entry...
If the entry is blank, just one or more whitespaces,
or is less than 3 characters in length then inform
the User of an invalid entry an to try again. */
if (name.isEmpty() || name.length() < 3) {
System.out.println("Invalid Entry (" + name + ")!\n"
+ "Name must be at least 3 characters in length!\n"
+ "Try Again...\n");
name = "";
}
}
/* If we get to this point then the entry meets our
validation rules. Now we get the first three
characters from the input name and display it. */
String shortName = name.substring(0, 3);
System.out.println();
System.out.println("Name supplied: --> " + name);
System.out.println("Short Name: --> " + shortName);
As you can see in the code above the String#substring() method is used to get the first three characters of the string (name) entered by the User.

Java input/output confusion

I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.

Search for a line in a file that matches the given condition

I'm writing a program for an assignment where the the user can search contents of a text file. The text file contains lines with Text and Numbers.
I want to prompt the user to enter a number, (e.g. a pin number), and a compare sign (=, <, >,)
I want to fetch and print where the number in the lines of file that matches the given number based on the given compare sign.
Here is what I have so far:
System.out.print("Enter integer: ");
String Value = input.next();
System.out.print("Enter type (=, <, >): ");
String Type = input.next();
while (file.hasNextLine())
{
String lines = file.nextLine();
if(lines.contains(Value))
{
if (compareType.equals(">"))
{
System.out.println(lines);
}
}
I appreciate any help you can give. Thanks.
Although I am not certain what you are asking, here is what I can give you from my understanding of your request.
You start off correctly getting the required values from the user.
System.out.print("Enter integer: ");
String val = input.next();
System.out.print("Enter type (=, <, >): ");
String operator = input.next();
while(file.hasNextLine()){
String line = file.nextLine();
if(operator.equals("=") && line.contains(val)){ //check if operator is equals and if line contains entered value
System.out.println(line);//if so, write the current line to the console.
}else if(operator.equals(">")){//check if operator is greater than
String integersInLine = line.replaceAll("[^0-9]+", " ");//we now set this to a new String variable. This variable does not affect the 'line' so the output will be the entire line.
String[] strInts = integersInLine.trim().split(" "))); //get all integers in current line
for(int i = 0; i < strInts.length; i++){//loop through all integers on the line and check if any of them fit the operator
int compare = Integer.valueOf(strInts[i]);
if(Integer.valueOf(val) > compare)System.out.println(line);//if the 'val' entered by the user is greater than the first integer in the line, print the line out to the console.
break;//exit for loop to prevent the same line being written twice.
}
}//im sure you can use this code to implement the '<' operator also
}

Regular Expression in Java: Validating user input

I am trying to validate user input using a regular expression in a while loop. I am trying to accept only one lower-case word (letters a-z inclusive).
public class testRedex{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Please enter a key: ");
while(!console.hasNext("[a-z]+")){
System.out.println("Invalid key");
console.next();
}
String test = console.next();
System.out.println(test);
}
}
My question is, is there any difference between having the regular expression as "[a-z]+" and "[a-z]+$"? I know that $ will look for a character between a-z at the end of the string, but in this case would it matter?
Yes there is a difference, if you'll use: ^[a-z]+$ it means that whatever the user inputs should be combined only from [a-z]+.
If you don't add the ^ and the $ the user could insert other characters, space for example, and there will still be a match (the first part of the string until the space.
Let's see an example:
run your code with the input: "try this" (it'll print "try")
now change the regex to ^[a-z]+$ and run with the same input (it'll print "Invalid key").
The way I would re-write it is:
System.out.print("Please enter a key: ");
String test = console.nextLine();
while (!test.matches("^[a-z]+$")) {
System.out.println("Invalid key");
test = console.nextLine();
}
System.out.println(test);
The difference are as follows
[a-z]+ means a,b,c,...,or z occurs more than one time
[a-z]+$ means a,b,c,...,or z occurs more that one time and must match end of the line
Yet at the end, they give you the same result.
if you want to understand it better try this
([A-Z])([a-z]+$)
It start with a capital letter and end with more than one time small letter
output:
Please enter a key: AAAAaaaa
Invalid key
Aaaaaa
Aaaaaa
Another way you can get the expected result from what you are looking for
code:
int i = 0;
String result = "";
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter your key:");
if(input.hasNext("^[a-z]+$")){
result = input.next();
i=1;
}else{
System.out.println("Invalid key");
}
}while(i==0);
System.out.println("the result is " + result);
output:
Enter your key:
HHHh
Invalid key
Enter your key:
Hellllo
Invalid key
Enter your key:
hello
the result is hello

Validation input to be string only and numbers only JAVA [duplicate]

This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 8 years ago.
I am a student and i have a little problem with validation inputs.
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
//If name contain other than alphabetical character print an error
double number;
System.out.println("Enter number:");
name = keyboard.nextDouble();
//If number contain other than number print an error
What i have tried is test to parse the string to double but i could not.
I have no idea how to test if the double is only number.
Please give me a clue of what i should do.
You can use Regular expression to check if the input match your constraint as follow :
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
if (!name.matches("[a-zA-Z_]+")) {
System.out.println("Invalid name");
}
String number;
System.out.println("Enter number:");
number = keyboard.nextLine();
if (!number.matches("[0-9]+")) {
System.out.println("Invalid number");
}
Here is a good tutorial to learn regex .
You can loop through each character of the String and check if it's not alphabetic using Character.isAlphabetic(char):
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name:");
String name = keyboard.nextLine();
for (char c : name.toCharArray()) {
if (!Character.isAlphabetic(c)){
System.out.println("INVALID");
break;
}
}
To only accept numbers, you can do something similar using the Character.isDigit(char) function, but note that you will have to read the input as a String not a double, or get the input as a double and the converting it to String using Double.toString(d).
double number = 0;
try {
number = Double.parseDouble(name)
} catch (NumberFormatException ex) {
System.out.println("Name is not a double.");
}
If number is not a double, you can catch a NumberFormatException.
It seems you are using scanner. If you are, you can use the Scanner class' hasNextDouble() to check if the input is a double before reading the double as shown below:
double number;
System.out.println("Enter number:");
if (keyboard.hasNextDouble()){
name = keyboard.nextDouble();
}
Have a look at the Scanner class docs for more information.
There is also the "fancier" regex solution.
Java Pattern Documentation
You can use this (untested code) given you used nextLine() for reading BOTH inputs:
boolean isWordOnly = Pattern.matches("\w*", name); //name is in your code
boolean isFloatOnly = Pattern.matches("\d*.?\d*", number); //number is in your code too
Now the too boolean values tell you if there is the desired format in your input. You can add it in a do - while loop or anything you want.
It is a good idea to start studying reg(ular) ex(presions) because they are useful in string formatting (Imagine that you have to test if the input is a valid email...). Also used to check for SQL injections and many key things in apps and programs generally.

Categories

Resources