java print result in english and other language - java

What I want to do is to print results in english and other language in java output.
Is there any "easy" way to do this other than copy paste the code and just translate the output in the language I need?
I am building a game with frequent input/output from the user and I would like to have the option the questions (output) to be in more than 1 languages. The input from users is only numbers, thus there won't be any differentiation there.
One way is to copy classes with output (printf) and translate them accordingly and ask user in the beginning of the game to choose the language, but in this case every time i make change in the code, I need to make those change in both copies of the code, thus making it more difficult.
Is there any shorter and more robust way?

Look at the java.text.MessageFormat class. It lets you define template messages with placeholders for data (like scores, user names, etc.) and then to repeatedly merge those messages with data to produce the kind of Strings you're looking for. The idea is that you'd have one set of templates for each language you want to support.

Related

React to console inputs (commands) - how to handle multiple options most efficient?

Some information (don't want to confuse you with a lot of shitty code):
I've done a pretty large console programm (my largest project so far) which helps me a lot with managing some accounts / assets and more. I'm constantly adding more features but at the same time I reshape the code to work on my shitty coding style.
The console program has a lot of commands the user can type and for every command different methods get called / objects get created / manipulated and so on.
My keywords which are saved in an ArrayList<String> and my commands have this type: [keyword] [...n more Strings]
DESIGN PROBLEM 1:
I have a method cmdProcessor(String[] arguments) which handles the input (command) of the user, and the [keyword] is always the first argument arguments[0]. That means I have a large number of if-statements of this type:
if(arguments[0].equalsIgnoreCase("keyword") callMethod(argmts); where in the String[] argmts the remaining arguments[1] ... [n] are.
Is this a good way to handle this or should I go with switch-case?
Or something else (what?)? Is it better to save the keywords in a HashMap<String, Method>?
DESIGN PROBLEM 2:
The methods (see above callMethod(argmts) ), which are triggered by the entered keyword look even more chaotic. Since the same method can have different numbers and forms of arguments saved in the String[] argmts the method is full of if(argmts.length == ...) to check length, and every of these if-blocks has a bunch of switch-case options which also have a lot of ifs and so on. The last else and the default-case in switch-case I always use for error-handling (throwing error codes and and explanation why the pattern doesn't match and so on).
Is this good or are there better ways?
I thought about using lots of submethods, which would also blow up
my program and cost a lot of time but maybe improve readability / overview. Is this okay, or what is the best
option in such cases (lots of ifs and switch-case)?
Since I want to build more and more around this program maybe I should start now to fix bad design before it's too late. :)
About Design-Problem 1:
My go-to would be to register a lot of Handlers, which you can base on a common interface and then implement the specific behavior individually. This is good, because the central method handling your input is slim, and you only need to register a lot of singletons once, on initialization. Disadvantage: if you forget one, it will not work. So maybe, you can register them automatically (reflection or something thelike).
Aside from that, a map is better than a List in this case, because (I assume) you don't need a sorting. You need a mapping from key to behavior, so a map seems better (though even a very large set of keywords would probably not be very inefficient, if you stick to a list).
About Design Problem 2:
If I was you, I'd use actual Regular-Expression patterns. Take a look at the java.util.regex.Pattern-class. You can isolate groups and validate the values you receive. Though it does not spare you the exception/error-handling, it does help a lot in segmentation and interpretation efforts.

Which way is it better to extract Account number and Balance from a SMS body?

I am planning a task to read all the Bank related SMS from the users android mobile inbox and extract their account number and balance from it. I am guessing this could be done in 2 ways as,
Using RegEx to extract the data from the SMS body as stated link here. This certainly has the advantage of giving generic representation of any Bank Balance message
Store a template message of every bank in the database and compare it with the read SMS to extract the data
I would like to know which path is efficient or Is there any other way to do it ?
The two approaches have different qualities:
Option 1 might lead to many different, complex regular expressions. Alone glancing into the answer you linked made my head spin. Meaning: maintaining such a list of regular expressions will not be an easy undertaking from the developer perspective.
Whereas for option 2, of course you have to keep track regarding your collection of "templates", but: once your infrastructure is in place, the only work required for you: adding new templates; or adapting them.
So, from a "development" efforts side I would tend to option 2 --- because such "templates" are easier to manage by you. You don't even need much understanding of the Java language in order to deal with such templates. They are just text; containing some defined keywords here and there.
One could even think about telling your users how to define templates themselves! They know how the SMS from their bank looks like; so you could think about some "import" mechanism where your APP pulls the SMS text, and then the user tells the APP (once) where the relevant parts can be found in there!
Regarding runtime efficiency: I wouldn't rely on people making guesses here. Instead: make experiments with real world data; and see if matching SMS text against a larger set of complex regular expressions is cheaper or more expensive than matching them against much simpler "templates".
Storing the template for each bank cost more memory (if you load them on at start up for efficiency) and file system storage, and also as you stated, there is the downside of requiring previous know each bank template and setup the user application properly to it.
Using the regex will not cost file system store neither more memory, however it could create false positives for something which looks like a bank message, but it is not. However there is the facility to not need to know all the banks out there in order to do it properly.

Localizing a legacy product?

Relatively simple question. I need to translate/localize a legacy Java application.
Our company, with newer applications uses .properties files in Java for localizing their strings, and this concept is very similar to .resx files in C# (which we also have products using that).
The problem is this is a legacy product that was around before we started thinking about localization. It is full of hard coded strings and also various forms of hard-coded string concatenation/formatting.
As far as I am aware I have a very daunting task of pulling all our strings and formatting into .properties files in the product and then referencing those in the code.
Personally I have no huge issue doing this work, but I want to make sure I am not missing something.
So I have a couple general questions.
Is there a faster way of converting my product to use the
.properties files? Off the top of my head I could write a script
that would automate maybe 30-40% of the work...
Are there any "gotchas" I should be worried about specific to converting a legacy
product (I am not looking for general localization "gotchas" which I
can google for, but anything specific to this scenario)?
Finally, are there any completely different strategies I am overlooking for
localization? This is just how we translate our existing products,
but because this is a legacy product (and on the agenda to be
re-written) this is essentially throw-away code and I could do pretty much whatever I want. Including just
finding the cheapest dirtiest fastest way possible, although I am
obviously leaning toward doing the job properly.
Any thoughts, people?
As a guideline I would say try to keep answers focused on the questions being asked, but any informational contributions or questions are always welcome in comments.
No, there is no faster way. You have to go through the code line by line.
There are plenty of gotchas, since internationalization is about more than just string constants.
You may already know that number formats and date formats need to be localized, but you'll need to be on the lookout for numbers and dates being embedded into strings via concatenation or StringBuilder.append calls. You'll also need to be on the lookout for implicit toString() calls, such as when a Number or Date is supplied as a Swing model value (for example, returning a Number from the TableModel.getValueAt method), or when a JSP or JSF EL expression refers to such a value directly instead of formatting it.
Similarly, keep an eye out for enum constants directly displayed to the user, implicitly invoking their toString() method.
Creating sentences through string concatenation is a problem not only because of the formatting of numbers, dates, and enums, but also because other languages may have different ordering of sentence structure. Such string concatenation should be replaced with localized MessageFormats.
Keystrokes need to be localized, including all mnemonics (and accelerators if it's a desktop app).
Layouts are an issue. Places where the application assumes left-to-right orientation are something you'll want to address; even if you're only planning to localize for other left-to-right languages, you probably know that putting off good i18n practices is asking for trouble later down the line.
If your app is a Swing application, you'll want to convert LEFT/WEST and RIGHT/EAST layout constraints to LINE_START and LINE_END. If your app is a web application, you'll need to factor out margin-left, margin-right, padding-left, padding-right, border-left, and border-right (and probably many others I'm forgetting) into lang-specific CSS blocks.
Swing apps also need to call applyComponentOrientation after building each window, usually right before calling pack().
Some programmers like to store parts of a UI in a database. I'm not talking about user content (which you shouldn't localize); I'm talking about label text, window titles, layout constraints, and so on. I have a hearty dislike for that practice, personally, but people do it. If your app is doing that, I guess either the database table needs a locale column, or the practice of storing the UI in the database needs to be removed entirely.
To answer your final question, if there are any better strategies than stepping through the code, I've never heard of them. You could just search for double-quote characters in the code, of course. I suppose the choice depends on how professional and polished your superiors want the application to look.
One thing I've learned is that throw-away code often isn't. Don't be surprised if that rewrite ends up trying to salvage large swaths of code from the legacy version.

How can I parse a basic Discrete Mathematical statement in Java?

I want to make a Java program to help people with basic discrete mathematics (that is to say, checking the truth values of statements). To do this, I need to be able to detect how many variables the user inputs, what operators there are, and what quantifiers there are, if any (∃ and ∀). Is there a good algorithm for being able to do all these things?
Just so you know, I don't just want a result; I want full control over their input, so I can show them the logical proof. (so doing something like passing it to JavaScript won't work).
Okay, so, your question is a bit vague, but I think I understand what you'd like to do: an educational aid that processes first-order logic formulas, showing the user step by step how to work with such formulas, right? I think the idea has merit, and it's perfectly doable, even as a one-man project, but it's not terribly easily, and you'll have to learn a lot of new things -- but they're all very interesting things, so even if nothing at all comes out of it, you'd certainly get yourself some valuable knowledge.
I'd suggest you to start small. I'd start by building a recursive descent parser to recognize zero-order logic formulas (a machine that would decide if a formula is valid, i.e. it'd accept "A ^ B" but it'd reject "^ A ^"). Next up you'd have to devise a way to store the formula, and then you'd be able to actually work on it. Then again, start small: a little machine that accepts valid zero-order logic formulas like TRUE AND NOT (TRUE AND FALSE), and successfully reduces it step by step to true is already something that people can learn from, and it's not too hard to write. If you're feeling adventurous, add variables and make equations: A AND TRUE = TRUE -- it's easy to work these out with reductions and truth tables.
Things get tricky with quantifiers that bind variables, that's where the Automated theorem proving may come into play; but then, it all depends on exactly what you'd like to do: implementing transformations into the various normal forms, and showing the process step by step to the student would be fairly easy, and rather useful.
At any rate, I think it's a decent personal project, and you could learn a lot from it. If you're in a university, you could even get some credit for it eventually.
The technique I have used is to parse the input string using a context free grammar. There are many frameworks to help you do this, I have personally used ANTLR in the past to parse an input string into a descrete logic tree. ANTLR allows you to define a CFG which you can map to Java types. This allows you to map to a data structure to store and evaluate the truth value of the expression. Of course, you would also be able to pull out the variables contained in the data structure.

Writing a program that will automate searches on finra.org for brokers

So I have two possible solutions that I want to implement. Firstly I will state my problem. The task I have been assigned to requires me to go to a website called finra.org and do broker checks to see if the brokers in my excel sheet(which gives the name and company among other things) still work A, and if they do work do they still work for the company in the excel sheet. If they do move on to the next one, and if they don't delete them from the sheet. The issue lies in that I have 37k names to check. I calculated this and to do it individually, which is annoying and takes the whole day allows me to do a maximum of 1400 a day. That is on a productive day when I dont have other things to do. So I figured a better use of my time ( I am an intern) would be to write a program which (here are my two suggested solutions:)
1.) Automatically through minimal key strokes copies the data and pastes it into the search box on the page. Ill still have to click and search but at least I would eliminate copying and pasting and switching between screens which takes the majority of the time.
2.) Completely automate the process. I was thinking of copying the names into a text file and then somehow writing a program that takes each name and submits a query to this website which would then show me the result. Perhaps sends the result text to a text file and then i could just GREP the text file for the data that i need.
Any idea if any of this is possible?
Thanks,
Kevin
Definitely possible. I'm doing something similar with a database and an Excel spreadsheet of values using AutoHotKey to automate queries, Chrome console commands and Javascript bookmarklets to scrape data into the clipboard, and Ruby/Nokogiri with more complex and/or structured parsing tasks.
Either of your methods will work - if you have little programming background, I would suggest starting with AutoHotKey since it mimics keyboard and mouse commands, so the programming is much more straightforward and easier to understand. If you have some object-oriented programming skills, learning Ruby/Nokogiri might be your solution, depending on how FINRA's page is structued.

Categories

Resources