I decided to write a simple calculator with several functions.
When you type help
an error occurs. Help me fix it and write why so, if you can, since I'm a newbie.
Here is the code
- What kind of error occurs? - delphist007
- oneException in thread "java.util.NoSuchElementException" at java.util.StringTokenizer.nextToken (Unknown Source) at Calculator.main (Calculator.java:53) - rberla
- oneWhat does "iterator move" mean? - rberla
- oneThe iterator is a StringTokenizer. Moves-means translates to next. the word user8539
|
3 answers
I’ve added a code that performs the actions of a very primitive calculator, I hope it will be useful for you
public class SimpleCalc { private static List<IAction> actions = new LinkedList<IAction>(); private static boolean DEBUG_MODE = true; static { actions.add(createAdd()); actions.add(createSub()); actions.add(createHelp()); } public static void main(String[] args) { // test usage if (DEBUG_MODE) { calc(null); calc(new String[] { "help" }); calc(new String[] { "1", "2", "3" }); calc(new String[] { "1", "+", "2" }); calc(new String[] { "5", "-", "4" }); } else { calc(args); } } private static void calc(String[] args) { IAction action = findAction(args); // handle result if (null != action) { System.out .println(argsToString(args) + "= " + action.perform(args)); } else { System.out.println("handling error case for args: " + Arrays.toString(args)); } } private static String argsToString(String[] args) { StringBuilder b = new StringBuilder(); for (String arg : args) { b.append(arg).append(' '); } return b.toString(); } private static IAction findAction(String[] args) { // no action if (null == args) { return null; } // find action for (IAction a : actions) { if (a.canApplyTo(args)) { return a; } } // action not found return null; } private static IAction createHelp() { return new IAction() { @Override public Object perform(String[] args) { return "Help system. Only next actions are allowed: add(+), sub(-)"; } @Override public boolean canApplyTo(String[] args) { return 1 == args.length && "help".equalsIgnoreCase(args[0]); } }; } private static IAction createSub() { return new IAction() { @Override public boolean canApplyTo(String[] args) { return 3 == args.length && "-".equalsIgnoreCase(args[1]); } @Override public Object perform(String[] args) { return Integer.parseInt(args[0]) - Integer.parseInt(args[2]); } }; } private static IAction createAdd() { return new IAction() { @Override public Object perform(String[] args) { return Integer.parseInt(args[0]) + Integer.parseInt(args[2]); } @Override public boolean canApplyTo(String[] args) { return 3 == args.length && "+".equalsIgnoreCase(args[1]); } }; } interface IAction { Object perform(String[] args); boolean canApplyTo(String[] args); } }
In order to work with command line arguments: DEBUG_MODE = false
.
The result of the test mode:
handling error case for args: null help = Help system. Only next actions are allowed: add(+), sub(-) handling error case for args: [1, 2, 3] 1 + 2 = 3 5 - 4 = 1
- oneExplain, please, the actions.add (createAdd ()); actions.add (createSub ()); actions.add (createHelp ()) ;, @Override, perform, since I'm new too - rberla
- 2actions contains a list of operations that our calculator can count. Therefore, in order for our calculator to be able to do anything, we add a list of 3 actions: processing the operations "help", "+", "-". Objects are created by corresponding methods - jmu
|
Error here
else if(StrTok.equalsIgnoreCase("help")){
The StrTokinizer object does not have an equalsIgnoreCase
method.
- 2I have a class StringTokenizer - rberla
- oneHow did it compile at all? - delphist007
- 2Compiled norms. - rberla
- oneReplaced with equals, still doesn't work - rberla
- 2Frankly, I do not understand why it was compiled with equalsIgnoreCase. With equals compiles, because it is inherited from Object. Error in accessing StrTok after StrTok.nextToken (). EqualsIgnoreCase ("bubblegum"), because nextToken "moves" iterator. You need something like if (StrTok.countTokens () == 1) {String s = StrTok.nextToken (); if (s.equalsIgnoreCase ("bubblegum") ... if (s.equalsIgnoreCase ("help") ... - avp
|
Do not use StringTokenizer
:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
If you want the way you wrote, then so here:
It should be like this:
else if(strTok.countTokens()==1){ String nextToken = strTok.nextToken(); if(nextToken.equalsIgnoreCase("bubblegum")){ System.out.println("Правильний пароль!"); } else if(nextToken.equals("help")){ System.out.println("Вітаємо!Ви завітали до довідки користувача калькулятора!" + "Подвійний приклад: 1 + 1 , 432 / 718, 321 - 4569"+ "Дії над числом (знаки, за їх відсутності на клавіатурі, замінено літерами) " + "Наприклад: 12 e , 16 w , 56 y" + "Довідка за позначеннями: q-квдрат w-корінь e-синус r-косинус t-тангенс y-катангенс "); }
- I recommend you use Enums. An example can be found in the book "Effective java" Joshua Bloch, Chapter 30 "Use enums instead of int constants". There just have an example with a calculator. - Anton Feoktistov
- StringTokenizer breaks a string into pieces. After that, you need to "go through" for each composer, and check whether it is up to the password, team or help. strTok.equalsIgnoreCase ("help"); - it does not compile strTok.equals ("help"); - and so you compare the string with an object of another type. - Anton Feoktistov
|