How to write interpretation of an expression in Java - java

So here is the part of my code:
if (file.toString().??? && file.toString().endsWith(FilterCommand.afterDot)) {
System.out.println(file.toAbsolutePath());
User will enter string, something like this(sometext.txt is just an example of one input, user will input several times and every time it can be something different): sometext.txt and my job is to find all files which match given expression. In this example it may be something like this:
sometext.txt
sometHhBkJnKext.txt
sometANYTHINGCANBEHEREext.txt
So "somet" and "ext.txt" remains constant. In between them anything can be there. I mean 0 or more characters. We can also assume that user will never input two *. It will always be one * and it can be at front, in the middle or in the end.
I am able to separate given string on string before dot(somet*ext, I save it in variable FilterCommand.beforeDot) and after dot(txt, I save it in variable FilterCommand.afterDot). So, in if I need to ask if the text after dot is same (I use:file.toString().endsWith(FilterCommand.afterDot) and if the text before dot match given expression. How can I do it?

So i think you can just do something like this -
if(file.toString().matches("somet.*ext\\.txt")){
System.out.println(file.toAbsolutePath());
}
else{
System.out.println("Not matching");
}

You can check it like this (This will also match the .txt so no need to split the filename):
public static void main(String[] args) {
if(Pattern.matches("somet.*ext\\.txt", "somet**HhBkJnK**ext.txt"))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
if(Pattern.matches("somet.*ext\\.txt", "sometext.txt"))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
if(Pattern.matches("somet.*ext\\.txt", "some**sdfsdfsdft**ex.txt"))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
Output:
Yes
Yes
No
Just do this to check with your file:
if(Pattern.matches("somet.*ext\\.txt", file.toString()))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}

Firstly, you need to escape the dot, i.e. \. otherwise the regex parser will interpret the dot as 'find a single character, any character'.
For example:
public static void main(String args[]) {
String regexFilePattern = "[[a-zA-Z0-9]+]\\.[[a-zA-Z0-9]+]";
Matcher matcher = null;
for(int i = 0; i < args.length; i++) {
matcher = Pattern.compile(regexFilePattern).matcher(args[i]);
while (matcher.find()) {
if (matcher.start() > 0) {
//there is a match!
//manipulate the result here when the text after the dot
//matches the text before the dot
}
}
}
}

I'm not sure why you would need to split the string that the user provides you at the '.'. It seems like you could just write file.toString().matches(userString)to determine if that file matches the provided pattern

Related

pattern matching in java using regex

In the program I am trying to look for pattern in content. If any of the pattern H Q 9 is found in string taken by user it should print YES else NO. So I used three bool flag1 flag2 flag3. My code gives wrong output if input is codeforces. Desired output is NO instead of YES.
public static void main(String[] args) {
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
Scanner in = new Scanner(System.in);
String s = in.nextLine();
String text = s;
String pat1 = ".*H*.";
String pat2 = ".*Q*.";
String pat3 = ".*9*.";
//boolean isMatch = Pattern.matches(pattern, content);
flag1 = Pattern.matches(pat1, text);
flag2 = Pattern.matches(pat2, text);
flag3 = Pattern.matches(pat3,text);
if (flag1 == true || flag2 == true || flag3 == true)
System.out.println("YES");
else
System.out.println("NO");
}
Your regexps are wrong - H* means "any number of Hs, including zero", and likewise for both other regexps.
Thus, .*H*. means that your text should contain an arbitrary number of "something", then an arbitrary number of Hs (or none, as "zero Hs" is also allowed), and then an arbitrary letter.
codeforces fulfils these criteria, as it contains of an arbitrary number of letters, no H and ends with an arbitrary letter.
Your regexps will match any input which has at least once character.
Using three regular expressions is redundant. I recommend just using one.
I also refactored and reformatted your code.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
boolean matches = Pattern.matches(".*[HQ9].*", s);
if (matches)
{
System.out.println("YES");
} else
{
System.out.println("NO");
}
}
You could compress the method even further:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
boolean matches = Pattern.matches("[HQ9]", s);
System.out.println(matches ? "YES" : "NO");
}
The regular expression .*[HQ9].* does the following: It searches for any characters equal to the ones found inside of the square brackets:
Although someone has already explained the problem (I do not want to take credit from others), here are a few suggestions to reduce and more importantly test your code
import java.util.regex.Pattern;
class Test75B {
public static final String[] TESTS = {
"codeforces",
"Back to Headquarters",
"A cat has nine lives",
"A cat has 9 lives",
"Is it a Query or a Quarry?",
"How Can You Quote 4+5=9!"
};
public static void main(String[] args) {
for (String text: TESTS) {
boolean flag1=false;
String pat1= ".*[HQ9].*";
System.out.println(text);
flag1=Pattern.matches(pat1, text);
System.out.println( flag1 ? "YES" : "NO");
}
}
}
Here is the output I get
codeforces
NO
Back to Headquarters
YES
A cat has nine lives
NO
A cat has 9 lives
YES
Is it a Query or a Quarry?
YES
How Can You Quote 4+5=9!
YES
As an easy test, remove the .* in the regex, recompile and look at the output. You will see they are required.

How can I check if my string is other than int's, to clarify i need to check it is not a number

... if instead of a number I get a letter, or a symbol, or 2 decimals.
I am making a change maker program in java.
Everything works good, the only thing i am confused about is checking the string to see if is invalid for my use,
I did this for when is left empty;
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "Invalid input! ");
System.exit(0);
}
That works perfect, now how can I do the else to check for letters or dots or symbols, anything that is not a number?
You could use regular expressions.
Here's some sample code to check for digits only (\\d) in your input string.
The code that actually checks is pattern.matcher(in).matches() and it tries to match the regular expression defined by regex
Let me know if you need more explanations
public class HelloWorld{
public static void main(String[] args) {
String regex = "\\d+";
String inputNumber = "2";
String inputDecimal = "2.0";
String inputString = "two";
String[] inputs = {inputDecimal, inputNumber, inputString };
Pattern pattern = Pattern.compile(regex);
for(String in: inputs){
System.out.print( in + " ");
System.out.print( pattern.matcher(in).matches()? "":"does not");
System.out.print( " contain integer numbers" );
System.out.println("---");
}
}
}
If you need to perform all the processing only when the String is integer why not check for integer value in the if clause and let the else clause be common for all the letter, dots, symbols and also empty.
if(s1.isNum){
//all processing here
}
else{
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Otherwise you could also use try and catch block.
try{
int num= Integer.parseInt(s1);
//rest of the processing
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Use either according to your requirement
You could use a regular expression1 and String.matches(String) which Tells whether or not this string matches the given regular expression. \\d+ should match one or more digits. Something like
System.out.println("12".matches("\\d+"));
Prints
true
1Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems. --jwz
To test whether it is an integer, parse it to an int like this:
Integer.parseInt(s1)
You might also want to make use of the value returned but I don't show it here. Now you can apply try catch blocks around the method call and catch NumberFormatException like this:
try {
Integer.parseInt(s1);
//The code here will run if s1 is an integer.
} catch (NumberFormatException e) {
//this will be executed when s1 is not an integer
}
You can also extract a method from the above code. A method that returns true when the exception is not thrown. However, a disadvantage of try catch is that throwing an exception needs time and thus, it slows down your program.
To test whether the string is a letter, you loop through all the chars in the string and use one of the methods of the Character class.
boolean isLetter = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isLetter(s1.charAt(i))) {
isLetter = false;
break;
}
}
If isLetter is true, it is a letter. Again, you can also extract this as a method.
To check whether it is a symbol, use one of the methods of the Character class (again).
boolean isSymb = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isJavaIdentifierStart(s1.charAt(i))) {
isSymb = false;
break;
}
}
To check for dots in a string, just use
s1.contains(".")
Isn't that simple?
Ok, I solved the problem the following way... I took a little bit of every idea lol...
if (s1 == null) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
for (int i = 0; i < s1.length(); i = i + 1) {
if (!Character.isDigit(s1.charAt(i))) {
JOptionPane.showMessageDialog(null, "You must enter an integer value");
System.exit(0);
}
}

Censored Words Condition

I need this program to print "Censored" if userInput contains the word "darn", else print userInput, ending with newline.
I have:
import java.util.Scanner;
public class CensoredWords {
public static void main (String [] args) {
String userInput = "";
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine;
if(){
System.out.print("Censored");
}
else{
System.out.print(userInput);
}
return;
}
}
Not sure what the condition for the if can be, I don't think there is a "contains" method in the string class.
The best solution would be to use a regex with word boundary.
if(myString.matches(".*?\\bdarn\\b.*?"))
This prevents you from matching sdarnsas a rude word. :)
demo here
Try this:
if(userInput.contains("darn"))
{
System.out.print("Censored");
}
Yes that's right, String class has a method called contains, which checks whether a substring is a part of the whole string or not
Java String Class does have a contains method. It accepts a CharSequence object. Check the documentation.
Another beginner method would be to use the indexOf function. Try this:
if (userInput.indexOf("darn") > 0) {
System.out.println("Censored");
}
else {
System.out.println(userInput);

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

check string for integers?

Ok, I posted once earlier but it was locked due to not demonstrating a basic understanding, and the answers I did get before it was locked didn't help me. I'm at a super beginner level of java and this is what I want my program to do (will post code at end). I want the user to input anything they want. Then, if it is not a number, I want it to display that they need to input a number. Then, after they input a number, I want it to display whether or not that number is even or odd. I read about parseInt and parseDouble but i can't figure out how to get it to work how I want. I am not sure any more if parsing is what i want to do. I dont want to instantly convert it to numbers, just to check if it IS a number. then i can proceed to do things after the program has determined if it is a character or number. thanks for any help and let me know if you need more information!
ok i changed some things and used a lot of code from no_answer_not_upvoted. here is what i have now. it runs fine and works with negative and positive whole numbers as specified in the directions. the only thing that bugs me is after all is said and done, i get this error in the compile box at the bottom of eclipse. the program does what is intended and stops appropriately but i dont understand why i am getting this error.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at monty.firsttry2.main(firsttry2.java:21)
public static void main(String[] args) {
System.out.print("Enter a character or number. This program will run until you enter a whole number, then it will"
+ "tell you if it was even or odd.");
while (true) {
Scanner in=new Scanner(System.in);
int num;
while(true) {
String input=in.nextLine();
try {
num=Integer.parseInt(input);
break;
}
catch (NumberFormatException e) {System.out.print("That wasn't a whole number. Program continuing.");}
}
if (num==0) {System.out.print("Your number is zero, so not really even or odd?");}
else if (num%2!=0){System.out.print("Your number is odd.");}
else {System.out.print("Your number is even");}
in.close();
}
}
}
Assumption
A String is to be considered a number if it consists of a sequence of digits (0-9), and no other characters, except possibly an initial - sign. Whereas I understand that this allows Strings such as "-0" and "007", which we might not want to consider as numbers, I needed some assumptions to start with. This solution is here to demonstrate a technique.
Solution
import java.util.Scanner;
public class EvensAndOdds {
public static final String NUMBER_REGEXP = "-?\\d+";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(;;) { // Loop forever
System.out.println("Enter a number, some text, or type quit");
String response = input.nextLine();
if (response.equals("quit")) {
input.close();
return;
}
if (response.matches(NUMBER_REGEXP)) { // If response is a number
String lastDigit = response.substring(response.length() - 1);
if ("02468".contains(lastDigit)) {
System.out.println("That is an even number");
} else {
System.out.println("That is an odd number");
}
} else {
System.out.println("That is not a number");
}
}
}
}
Justification
This solution will match a number of ANY length, not just one that will fit into an int or a long; so it is superior to using Integer.parseInt or Long.parseLong, which both fail if the number is too long. This approach can also be adapted to more complicated rules about what constitutes a number; for example, if we decided to allow numbers with comma separators (such as "12,345" which currently will be treated as not a number); or if we decided to disallow numbers with leading zeroes (such as "0123", which currently will be treated as a number). This makes the approach more versatile than using Integer.parseInt or Long.parseLong, which both come with a fixed set of rules.
Regular expression explanation
A regular expression is a pattern that can be used to match part of, or all of a String. The regular expression used here is -?\d+ and this warrants some explanation. The symbol ? means "maybe". So -? means "maybe a hyphen". The symbol \d means "a digit". The symbol + means "any number of these (one or more)". So \d+ means "any number of digits". The expression -?\d+ therefore means "an optional hyphen, and then any number of digits afterwards". When we write it in a Java program, we need to double the \ character, because the Java compiler treats \ as an escape character.
There are lots of different symbols that can be used in a regular expression. Refer to http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html for them all.
this shows you how to do it
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
try (Scanner in = new Scanner(System.in)) {
int n;
while (true) {
String input=in.nextLine();
try {
n = Integer.parseInt(input);
break;
} catch (NumberFormatException e) {
System.out.println("you did not enter just an integer, please try again");
}
}
if (n % 2 == 0) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
}
}
}
As is already mentioned in other answers, you will need to call parseDouble statically with
Double theNumber = Double.parseDouble(numberString);
Next you will want to look at wrapping this in a try/catch so that you can do the even/odd check if theNumber is created or set the error message if an exception is caught.
Since you are a beginner, you need to understand the difference between numbers (integers, double, strings, characters), so the following will guide you.
First, read input one line at a time,
Java read line from file)
Then scan line looking for characters that form what you consider to be an integer (allow leading spaces?, then '+' or '-', then digits 0-9, and then trailing spaces.
Here are the rules (for integers)
leading spaces ok (this is up to you) (how: How to check if a char is equal to an empty space?)
optional single '+' or '-'
one or more digits (how: How to check if a character in a string is a digit or letter)
optional trailing space(s) (again, this is up to you)
Anything other than this pattern violates the test for 'is this an integer'. Btw, Double is an extended precision real number.
import java.lang.*;
import java.util.Scanner;
public class read_int
{
public static boolean isa_digit(char ch) {
//left as exercise for OP
if( ch >= '0' && ch <= '9' ) return true;
return false;
}
public static boolean isa_space(char ch) {
//left as exercise for OP
if( ch == ' ' || ch == '\t' || ch == '\n' ) return true;
return false;
}
public static boolean isa_integer(String input) {
//spaces, then +/-, then digits, then spaces, then done
boolean result=false;
int index=0;
while( index<input.length() ) {
if( isa_space(input.charAt(index)) ) { index++; } //skip space
else break;
}
if( index<input.length() ) {
if( input.charAt(index) == '+' ) { index++; }
else if( input.charAt(index) == '-' ) { index++; }
}
if( index<input.length() ) {
if( isa_digit(input.charAt(index)) ) {
result=true;
index++;
while ( isa_digit(input.charAt(index)) ) { index++; }
}
}
//do you want to examine rest?
while( index<input.length() ) {
if( !isa_space(input.charAt(index)) ) { result=false; break; }
index++;
}
return result;
}
public static void main(String[] args) {
System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
Scanner in=new Scanner(System.in);
String input=in.nextLine();
if( isa_integer(input) ) {
System.out.print("Isa number.");
}
else {
System.out.print("Not a number.");
}
}
}

Categories