The user must enter any expression as a formula. For example, a + b + c-d + f that the user enters into the console. If the user enters the wrong formula, that is, a + df + sdfg or + a + 5 + b + c //, then an exception should be raised that the formula has the wrong structure. The formula should consist only of letters of the alphabet and signs. Numbers should not be and should be entered only small letters.

String sIn = null; Scanner in = new Scanner(System.in); System.out.println("Введите формулу: "); sIn = in.nextLine(); boolean flag=true; for (int j = 0; j < d.length(); j++) { ch = d.charAt(i); String s = Character.toString(ch); if(s.matches("[az]")&& Character.toString(d.charAt((d.length()-1))).matches("[az]")){ // ..... } else new Throwable("Неправильная структура формулы"); 

here only the first and the last letter of the alphabet is checked. But if the user enters a letter without letters or large letters, then the exception does not pop up. Thank.

If you do this:

  boolean bool =true; char ch,chfirst, chlast; String str="a+b-c+a"; chfirst = sIn.charAt(0); chlast = sIn.charAt(sIn.length()-1); if(Character.toString(chfirst).matches("[az]")&& Character.toString(chlast).matches("[az]")){ for (int j = 0; j < sIn.length(); j++) { ch = sIn.charAt(j); if(j%2==0 && Character.toString(ch).matches("[az]")){ bool = true; } } } else bool = false; System.out.println(bool); 

then the result is more desirable, but if you enter not a letter of a letter and together for example aa + bb + c-r + d, then the result also gives true. How to make it so that only letters can be entered separately, for example, d + b + ac? Thank.

  • 2
    Very interesting task! The parser of arithmetic expressions should be written in your life at least once by any student. And what is the question? - VladD
  • @VladD, let's go on regexp) - Nofate
  • @Nofate: Too easy! :-) Yes, and in ideone debugging is inconvenient. - VladD
  • question how to do it easier - Mack
  • made a change but still not exactly the desired result - Mac

2 answers 2

An article about regular expressions. Use the matcher method and you will be happy. In fact, you will have something like this:

 package stackowerflowstring; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StackOwerflowString { public static String str = ""; public static void main(String[] args) { str = "a"; System.out.println(str + " " + test(str)); //true str = "a+b"; System.out.println(str + " " + test(str)); //true str = "ab"; System.out.println(str + " " + test(str)); //true str = "a*b"; System.out.println(str + " " + test(str)); //true str = "a/b"; System.out.println(str + " " + test(str)); //true str = "a+b-"; System.out.println(str + " " + test(str)); str = "a+bb"; System.out.println(str + " " + test(str)); str = "a+D"; System.out.println(str + " " + test(str)); str = "a+rb"; System.out.println(str + " " + test(str)); //true } public static boolean test(String testString){ Pattern p = Pattern.compile( //начало формулы, может быть одна буква "^[az]" //регулярное выражение вида +а, неограниченное кол-во раз + "([+|\\-|*|/][az])*" ); Matcher m = p.matcher(testString); return m.matches(); } } 
  • Thank you very much! only in order not to allow 1 letter I added instead of {1,} $ instead of * - Mac
  • You could just put + instead of a star. This is from one inclusive - FoeNicks
  • but what if the expression contains brackets for example d + (b + a) * c? Can this check also be done with regex? - Mac
  • There is such a way - reverse Polish entry. habrahabr.ru/post/100869 - described here, go for the seed. And so - you need a parser that simply rewrites the string in the reverse Polish entry. - FoeNicks
  • I will try to write an example with brackets a bit later, it's time to work) - FoeNicks

The main class, for input from the console, I think it is clear how to modify:

 package consolejava; public class consolejava{ public static void main(String[] args) { String str = "QUOTE+QUOTE+a+(a+d+(s+d))"; if(str.contains("(")) System.out.println(str + " " + CheckRegular.test(checkString.CheckStr(str))); else System.out.println(str + " " + CheckRegular.test(str)); } } 

Class for checking the accuracy of the expression, a slight modification of the previously described algorithm:

 package consolejava; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckRegular { private static String str = ""; public static boolean test(String testString){ Pattern p = Pattern.compile( //начало формулы, может быть одна буква или ключевое слово, обозначающее выражение в скобках "^([az]|QUOTE)" //регулярное выражение вида +а, неограниченное кол-во раз + "([+|\\-|*|/]([az]|QUOTE))*" ); Matcher m = p.matcher(testString); return m.matches(); } } 

Class for searching expressions in brackets:

 package consolejava; public class checkString { private static String stringInQuote = ""; private static Integer indexClose = 0, indexOpen = 0; private static boolean FLAG = false; public static String CheckStr (String s) { //ищем первую закрывающую скобку indexClose = s.indexOf(")"); if(indexClose.equals(-1))return "ERROR"; //ищем открывающую скобку для нее indexOpen = s.lastIndexOf("(", indexClose); if(indexOpen.equals(-1))return "ERROR"; //вытаскиваем строку и проверяем ее на правильность stringInQuote = s.substring(indexOpen + 1, indexClose); FLAG = CheckRegular.test(stringInQuote); //если правильно, заменим выражение в скобках ключевым словом if(FLAG) stringInQuote = s.substring(0, indexOpen) + "QUOTE" + s.substring(indexClose + 1); //иначе возвращаем значение, которое вызовет ошибку(ключевое слово ошибки) else return "ERROR"; //если в строке еще есть скобки, рекурсивно обработаем строку if(stringInQuote.contains(")"))stringInQuote = CheckStr(stringInQuote); //иначе вернем строку return stringInQuote; } }