Java - Scanner doesn't read string with space (Solved) - java

I am trying to allow an input that is only made with characters a-zA-Z and also haves space. Example: "Chuck Norris".
What happens with the code below is that the scanner input.next() doesn't allow the mentioned example input string.
I expect this output: Success! but this is the actual output: Again:
try {
String input_nome = input.next(); // Source of the problem
if (input_nome.matches("[a-zA-Z ]+")) {
System.out.print("Success!");
break;
} else {
System.err.print("Again: ");
}
} catch (Exception e) {
e.printStackTrace();
}
SOLUTION
The source of the problem is the used scanner method.
String input_nome = input.next(); // Incorrect scanner method
String input_nome = input.nextLine(); // Correct scanner method
Explanation: https://stackoverflow.com/a/22458766/11860800

String t = "Chuck Norris";
t.matches("[a-zA-Z ]+")
Does in fact return true. Check for your input that it actually is "Chuck Norris", and make sure the space is not some weird character. Also instead of space, you can use \s. I also recommend 101regex.com

Please refer this link :
Java Regex to Validate Full Name allow only Spaces and Letters
you can use the below Regular Expression
String regx = "^[\\p{L} .'-]+$";
This should work for all scenarios and unicode.

Related

how to check if a user's input follows the correct format

I want to write a program to ask the user's age, gender, name. Are there any simpler methods which I can use to check if the input is following the correct format?
The correct format is: name -- age -- gender
For example, Bob -- 22 -- M
public static void main (String[] args){
Scanner scan = null;
String info = null;
while (true){
scanner = new Scanner (System.in);
info = scanner.nextLine();
if (!info.contains("--") || !info.contains(" ")){
System.err.println("invalid format");
continue;
}
String infoList = info.split("--");
// I need to check if the input contains any other sign such as ~,! and if there are
// exactly 3 inputs
// so the list should be {X,Y,Z}, I also need to check if the age is a number rather
//than a letter or a sign.
}
If I write my program like that (use if condition to check every possible invalid condition), which will make my program long-winded.
Best way to do it would be using regular expressions rather than splitting the string into and array and checking each item indidually.
This regex should work:
[A-Za-z]+ -- [0-9]{1,2} -- [MF]
You can then check if any string matches this expression
String regex = "[A-Za-z]+ -- [0-9]{1,2} -- [MF]";
String testString = "Bob -- 22 -- M";
if(testString.matches(regex)) {
// testString matches the regex
} else {
// testString doesnt match the regex
}
After checking that the expression matches you could split the string and be able to manipualte each of the elements individually. Remeber to split by " -- " rather than "--" else you will get spaces in the string which can give problems later when manipulating the data.
If you want to understand better how regex works I would recommend you to search a bit about it as it can be very useful.
You can use Regex
String info = "Bob--22--M";
if (info.matches("[a-zA-z]+--[0-9]{2}--[MFmf]")){
System.out.println("invalid format");
}
See regex here
You can do a simple method for each verification and then only call that method.
String[] infoList = info.split("--");
// infoList[0]should be the name, infoList[1] should be the age and infoList[2] should be the gender
if(!checkFormat(infoList[1],infoList[2])){
System.out.println("invalid format");
return;
}
method for verification:
private boolean checkFormat(String age, String gender){
try
{
int aux =Integer.parseInt("age");
}
catch(Exception)
{
return false;
}
if(!(gender.Equals("M") || gender.Equals("F")))
{
return false;
}
return true;
}
About the name, unless you have some especification, I can't do nothing about it.

Can I use startsWith and endsWith in Java to check input?

In Java can I use startsWith and endsWith to check a user input string? Specifically, to compare first and last Characters of the input?
EDIT1: Wow you guys are fast. Thank you for the responses.
EDIT2: So CharAt is way more efficient.
So How do I catch the First and last Letter?
char result1 = s.charAt(0);
char result2 = s.charAt(?);
EDIT3: I am very close to making this loop work, but something is critically wrong.
I had some very good help earlier, Thank you all again.
import java.util.Scanner;
public class module6
{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(true){
System.out.print("Please enter words ending in 999 \n");
System.out.print("Word:");
String answer;
answer = scan.next();
char aChar = answer.charAt(0);
char bChar = answer.charAt(answer.length()-1);
String MATCH = new String("The word "+answer+" has first and last characters that are the same");
String FINISH = new String("Goodbye");
if((aChar == bChar));
{
System.out.println(MATCH);
}
if(answer !="999")
{
System.out.println(FINISH);
break;
}
}
}
}
The loop just executes everything, No matter what is input. Where did I go wrong?
In Java can I use startsWith and endsWith to check a user input string?
You certainly can: that is what these APIs are for. Read the input into a String, then use startsWith/endsWith as needed. Depending on the API that you use to collect your input you may need to do null checking. But the API itself is rather straightforward, and it does precisely what its name says.
Specifically, to compare first and last Characters of the input?
Using startsWith/endsWith for a single character would be a major overkill. You can use charAt to get these characters as needed, and then use == for the comparison.
yes, you should be able to do that and it should be pretty striaghtforward. Is there a complexity that you are not asking?
Yes, in fact, not just characters, but entire strings too.
For example
public class SOQ4
{
public static void main(String[] args)
{
String example = "Hello there my friend";
if(example.startsWith("Hell"))
{
System.out.println("It can do full words");
}
if(example.startsWith("H"))
{
System.out.println("And it can also do letters");
}
if(example.endsWith("end"))
{
System.out.println("Don't forget the end!");
}
if(example.endsWith("d"))
{
System.out.print("Don't forget to upvote! ;)");
}
}
}
I recommend you use the API, here's a link to it http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Java substring in a string

I know this has question has been asked countless times.. but I can't seem to get it to work. the problems are,
Even converting everything to lower case doesn't work out when
"computer" and "Comp" are entered.
If the string is a sentence (I add a space), it essentially skips the substring code and says "Not in the string"..
Help is appreciated.
thanks!
Scanner in=new Scanner(System.in);
System.out.println("\fEnter the main string:");
String GivenString=in.next();
System.out.println("Enter the substring :");
String SubString=in.next();
GivenString.toLowerCase();
SubString.toLowerCase();
if(GivenString.indexOf(SubString)!=-1)
{
System.out.println("Substring is in the given string.");
}
else
{
System.out.println("Substring is not in the given string.");
}
Strings are immutable and toLowerCase() returns a new String object. These lines:
GivenString.toLowerCase();
SubString.toLowerCase();
...do not modify the values in GivenString and SubString.
You would need to modify them to:
GivenString = GivenString.toLowerCase();
SubString = SubString.toLowerCase();

Read data in from text file, convert each word to PigLatin

I'm having trouble printing out the final result without each word being on its own line. The output should be formatted just as the input was. Here is the code I used to read the data and print it:
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(dataFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
boolean b;
while (b = s2.hasNext()) {
String s = s2.next();
System.out.println(pig(s));
}
}
The actual instructions were as follows: "Translate the Declaration of Independence ("declaration.txt") into PigLatin. Try to preserve the paragraphs. There are several ways to do this, but they all use nested loops. You may want to look at nextLine, next, split, or StringTokenizer."
We haven't been taught how to use any of the methods listed there, though.
The println method is short for "print line". It prints the given output to the target output device followed by a newline. Check out the other methods in that class for the solution.
Update
The problem here is that to my knowledge java.util.Scanner throws out the whitespace (delimiter) between words. Check out java.util.StringTokenizer for a similar class that can be configured to return the whitespace characters one at a time.

Get the last line from a String containing many lines

I'm reading a text file line by line and converting it into a string.
I'm trying to figure out how to check if the last line of the file is a specific word ("FILTER").
I've tried to use the endsWith(String) method of String class but it's not detecting the word when it appears.
Rather naive solution, but this should work:
String[] lines = fileContents.split("\n");
String lastLine = lines[lines.length - 1];
if("FILTER".equals(lastLine)){
// Do Stuff
}
Not sure why .endsWith() wouldn't work. Is there an extra newline at the end? (In which case the above wouldn't work). Do the cases always match?
.trim() your string before checking with endsWith(..) (if the file really ends with the desired string. If not, you can simply use .contains(..))
public static boolean compareInFile(String inputWord) {
String word = "";
File file = new File("Deepak.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
word = input.next();
if (inputWord.equals(word)) {
return true;
}
}
} catch (Exception error) {
}
return false;
}
With
myString.endsWith("FILTER")
the very last characters of the last line are checked. Maybe the method
myString.contains("FILTER")
is the right method for you? If you only want to check the last ... e.g.20 chars try to substring the string and then check for the equals method.

Categories