Throw Exception for unsupported characters [duplicate] - java

This question already has answers here:
How to check if a String contains only ASCII?
(14 answers)
Closed 3 years ago.
I have user input
private Scanner inn = new Scanner(System.in);
String input = inn.nextLine().toLowerCase();
and i need to throw IllegalCharacterException(own exception, created this class already) for not desired input (all numerals and symbols and maybe even other languages)I need only english letters. How can i do that? Thank you.

You can use String.matches(String regex) with regular expressions. E.g.
private Scanner inn = new Scanner(System.in);
String input = inn.nextLine().toLowerCase();
if(input.matches("[a-z]*")) {
// Do some stuff
}
The Regular expression [a-z]* matches any character from a to z (lowercase), without any numbers, symbols or spaces.

Related

Removing all certain characters from an ArrayList [duplicate]

This question already has answers here:
Remove all non alphabetic characters from a String array in java
(9 answers)
Removing all characters but letters in a string
(4 answers)
Closed 4 years ago.
How do you remove all certain elements or characters from an ArrayList?
Let's say I have a scanner object like
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.nextLine();
And the user inputs something like
Bubblesort.=
If I wanted to save the characters of the String variable to an ArrayList, I'd use a char ArrayList and then load the characters in using a for loop like so
ArrayList<Character> stringArrayList = new ArrayList<Character>();
for (int i = 0; i < userInput.length(); i++) {
stringArrayList.add(userInput.charAt(i));
}
My question is, how do I remove all the characters which aren't letters. Like '.', and '=' so that the ArrayList contains only the word "Bubblesort"?

Length method in java , when used on input string does not produce the expected result [duplicate]

This question already has answers here:
Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class
(24 answers)
Closed 5 years ago.
My initial code that does not produce the desired result:
import java.util.Scanner;
class Strings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your word: ");
String word1 = sc.next();
System.out.println(word1.length());
sc.close();
}
}
Output:
tk#localhost:~$ java Strings
Enter your word:
avada kedavra
5
Which is not the length of my string.
But when I try this(without the user input) :
class Strings {
public static void main(String[] args) {
String str = new String("avada kedavra");
System.out.println(str.length());
}
}
Output :
tk#localhost:~$ java Strings
13
It works!
So , why doesn't it work when I take input from the user? What am I missing?
By default, sc.next() finds and returns the next complete token. By default, a token is a word, something separated with spaces or newline (\p{javaWhitespace}+).
So in your first example, word1 = "avada", with length 5.
Use sc.nextLine() to get the complete line.
In short: RTFM
A bit longer for the click-lazy: Scanner returns the "next token" when calling next Tokens are calculated by taking a pattern, which is "all whitespaces" by default. So your call of next returns the next word and not the complete line as you intended.
Set a fitting pattern when instantiating Scanner or call nextLine instead.

Search String in file [duplicate]

This question already has answers here:
Creating a Java Program to Search a File for a Specific Word
(3 answers)
Closed 5 years ago.
I am trying to count the number of times a specific string appears into a file.
This is the code I am using:
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(wordidnamee1))
count++;
}
This code only counts the number of time the string appears 'clean', but if it is attached to another word or followed by a colon it is not counted.
How can I solve this problem ?
Use contains()
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.contains(wordidnamee1))
count++;
}
For Non Case Sensitive match:
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.toLowerCase().contains(wordidnamee1.toLowerCase()))
count++;
}

How to take multiple string value as input? [duplicate]

This question already has answers here:
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 5 years ago.
I have a string variable that I use to get input values. for ex.
Scanner in=new Scanner(System.in);
varName=in.next();
when I give value as (John jony) it only displays John. Any way to get whole string?
Use the following instead:
Scanner in=new Scanner(System.in);
String text = in.nextLine();
System.out.println( text );
"in.nextLine()" reads in a whole line

How to only accept a specific format of numbers from the user in Java? [duplicate]

This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 7 years ago.
How can I make it so input from the user will only be accepted if the format is exactly "xxx-xxx-xxxx" where x can be any number, but only numbers, and the dashes have to be there, in those groupings. Basically, it's supposed to accept phone numbers. Right now I have:
Scanner input = new Scanner(System.in);
String in = input.next(); // Stores user input as a string
if (in.contains("[a-zA-Z]") == false && in.length() == 12) {
System.out.println("Number Accepted");
} else {
System.out.println("Number Rejected");
}
Currently, it will reject numbers that are greater or less than 12 characters, but it will accept anything that is 12 characters, even if it has letters. I also do not a solution to grouping the numbers with the dashes correctly, as the user should only be able to input 3 numbers, then a dash, then 3 more numbers, then a dash, and then finally 4 numbers.
You could use a Pattern to apply a regular expression:
Pattern pattern = Pattern.compile("^\d{3}-\d{3}-\d{4}$");
Scanner input = new Scanner(System.in);
String in = input.next(); // Stores user input as a string
if (pattern.matcher(in).matches())) {
System.out.println("Number Accepted");
} else {
System.out.println("Number Rejected");
}

Categories