How to keep the for-loop counter at 0; BigDecimal; etc - java

I have been trying to complete the following assignment for my college. So far, I have received help on this assignment a couple of times (which I really appreciate).
Since this is an assignment for college, I would appreciate non-direct answers that explain the concepts with examples that don't directly fix my assignment.
The assignment requires me to check for some things depending on user input.
If the user inputs an order, then inputs the same order with the same code again, it replaces the previous information with the new one. EG, if the user inputs G22 as code and 5 as quantity, then again enters G22 and then 4 as quantity, it forgets about the 5 and replaces that with 4. How can I make it so it remembers the previous one and simply adds the new order and makes it Quantity = 9 (I am using arrays for user input).
If the user enters G22 and quantity 3, but then doesn't enter anything and just hits enter, the counter adds one and upon pressing X (to quit) the shipping charges show up as $2.00 which is for 2 items. How can I avoid the counter from adding 1 in case nothing sensible is entered, i.e. anything else apart from the 4 options available is entered.
I understand that using doubles is not advisable for anything related to money and BigDecimal is recommended (alongwith NumberFormat, maybe). Can I replace my current doubles with BigDecimal with minimal problems, or do I have to replace the whole code? I also do not understand how to implement BigDecimal that easily so I would appreciate layman examples on that (especially on whether I can add/subtract/multiply/divide BigDecimal with ints etc).
I would post the code here but I don't want it copied by anyone else doing the same course and then submit it before I do (not that my code is the most awesome thing in the world, I just put in a lot of effort since its my first ever program).

1) I would use a Map<String, Integer> to store all the quantities for a product code.
2) I would get the total of items ordered by summing the quantities in the map. How the user enters the data shouldn't matter.
3) This advice is project dependant. In your case the option of the marker is what matters. Working in investment banks and trading firms for many years, and I haven't seen anyone use BigDecimal for money. Its not a major rewrite, and at a minimum you should know how to use both double and BigDecimal handling rounding correctly.

Related

Increment Database with multiple conditions

I'm extremely new to coding, and I need to solve a problem that I'm not sure what is the best approach. I'd appreciate enormously if anyone could point me towards a proper solution!
The problem is: I have a bunch of list of numbers (aprox. 2 thousand) each containing 6 digits, from 1 to 20, like this:
1 {1,13,5,16,4,19};
2 {2,5,9,15,22,8};
3 {14,23,1,13,6};
...
they never repeat within the same list.
I need to add new lists, that should be generated based on information from the 2k previous (I have it in an excel sheet). For example:
The next list (6 numbers, 1 to 20), need to match a given sum (and this sum will be the most frequent sum in my database);
They need to start with a number (for instance,1);
They must contain at least 3 odd numbers;
I have no idea what coding language would be best to use, I'm dedicating my time learning some Python and C#, and see if I can come up with a solution, but I'm really struggling to understand whether these languages are suitable for the problem or not.
Thanks a lot in advance to anyone willing to shed some light on my problem!

Auto-correcting an inputted String value, in java

I have a simple application that asks the user for a search term, and then performs a search for that term.
I want to give it the ability to "auto correct" the entered term. This is just for a few terms, that are easy to enter incorrectly. For example, if someone searches for "BestBuy", and what I have in my array to be searched is "Best Buy", I want to automatically convert "BestBuy" into "Best Buy" before the search. I intend to have a list of these in a text file.
What's the best way to do this? Can I have in my text file, every line be something like bestbuy, Best Buy the first item being the entered term and the second one being what it gets autocorrected into? What should I use to store this data? A hashmap?
Edit: Just to clarify, I'm not trying to make an actual auto-correct system. That's way, way beyond the scope of this project. This is just to simply replace certain inputs with "corrected" versions to match what is in the array being searched.
Autocorrect, generally has a harder solution than a hashmap, because you cannot predict the user input, so no point of making a hashmap, though you can use it as a key-existence store.
One possible way: http://en.wikipedia.org/wiki/Levenshtein_distance with the words you have in your map/dictionary, and then selecting the nearest
you could use HashMap, create a method that translate all different types of input into the correct one. You method takes input like bestbuy, best buy, BestBuy,etc and return only Best Buy. The result Best Buy will be the HashMap key.
This is bit tricky. To give a high level idea, you need to maintain a hashMap, with string without spaces as key, and the corrected value as value. when user enters a string, trim() it, check with your map' keyset, and replace with value if found matching entry.

query for Math.random to generate only a certain amount of each number needed

I am curious if anyone knows a way to use math.random to generate random numbers between say 0 and 3, But when it generates two 0's or two 1's it rules out the possibility of generating them numbers?
This is for a game assignment for college and all I have left to do is set it that it only generates two of each number with one 3. If anyone knows how this would be very helpful (even if it is using something other than math.random.
The language is Java.
So, you basically want to keep track of the number draws, right?
A possible solution is to use an array whose length is the valid range of your random numbers, where each cell counts the occurrences of the respective number. Then, for each draw, you check the contents of the respective cell in the array to see if you reached the limit. If you did, then redraw and repeat.
Note: at the time of writing this, the language of use is unknown, but the solution is generic enough to be implemented in virtually any language that provide a random() function.

Querying for today, within a week, and within a month

I'm new. I'm writing an app for a laser tag place where we've got kids of many ages coming to shoot beams at each other. We're making a highscore screen that'll display the best scores of the day, of the week, and of the month. The idea is that people will feel proud being on the list, and there'll also be prizes once a month.
I'm getting stuck at the whole filtering by date thing.
I basically modified the classic guestbook example to the point where I can add scores and customer info, and sort them by score.
Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
String fornavn = req.getParameter("fornavn");
Integer score = Integer.parseInt(req.getParameter("score"));
String email = req.getParameter("email");
String tlf = req.getParameter("tlf");
Date date = new Date();
Entity highscore = new Entity("Greeting", guestbookKey);
highscore.setProperty("date", date);
highscore.setProperty("fornavn", fornavn);
highscore.setProperty("score", score);
highscore.setProperty("email", email);
highscore.setProperty("tlf", tlf);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(highscore);
And in the jsp there's a query that grabs the overall top 5.
Query query = new Query("Highscore", highscoreKey).addSort("score", Query.SortDirection.DESCENDING);
List<Entity> greetings = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
And there's a form that sends the user input to the .java. Any tips as far as how I should set up the dates? Saving week # and month # and querying based on that? Seems cumbersome.
From what I can tell, your "HighScore" kind is actually a "Score" kind that keeps track of all scores.
Instead of querying for the high score for the week/month, you're probably better off having a single HighScore entity (that's separate from normal "Score" entities) that you update whenever you enter a score. Every time a new score is entered, check if the high score should be updated.
You never need a fancy query, you just need to fetch the high score entity.
Or you might want a separate high score entity for each month/week etc so you can keep track of the history. In this case you may want to encode week or month into the entity key, so you can get the current week/month's HighScore easily.
There are 2 possible approaches for a requirement like yours where you want to show highscores for a day, week, month, etc:
1, First option is to use your current model where you are storing date and score. Since app engine allows inequality filter only on 1 property, you need to apply an inequality filter on date and then find the n highest number of scores. But since the result will be sorted first for the property with inequality filter and then for any additional property, you cannot do a fetch for only the first n entries to find the top n because the top scores need not be in continuous order. See this post to understand this better. So you will have to fetch all the scores for the date range and then do further sorting of the query result at your client to find the top n. This approach is ok if the total number of scores for a week or a month will not be too high compared to the value of n. If not, this is not a scalable option.
2, Second approach is to redesign your model such that sorting happens on scores so that for getting top n scores for a particular period, you need to fetch only the first n entries. This means the approach is suitable even if number of scores are very large. This then requires converting your date to be suitable for equality filtering like for each entry storing a month number, a week number and calendar year. Then for example if you want to find the top n scores in the 3rd month, then you can query for month=3, sort by scores descending and fetch the first n matching entries. Similarly you can query for a particular week using a week number.
This is very similar to another high-score SO question. I have copied/pasted my answer to it below. Approaching this solution using a database query may cause you to join the ranks of folks who complain about GAE. You will be using a custom index. Your query will likely average 10x miliseconds slower than needed per request. You will need to index thousands, perhaps millions of records. This costs you money -- perhaps lots of it both re: data storage (indices) and instances due to your high latency for what will likely be a highly-called handler function. Think different please. My copy/paste is not as specific to your setup, but it can be easily extended easily. I hope that it might prompt you to think about lower resource, lower cost alternative. As always...HTH. -stevep
Previous high score answer:
You may want to consider an alternate approach. This is a lot of index overhead which will cause your costs to be higher, the response time for the handler executing this function to operate an order of magnitude slower and you will have moments where the eventual consistency of index updates will affect maintenance of this data. If you have a busy site, you will surely not be happy with the latency and costs associated with this approach.
There are a number of alternate approaches. Your expected site transactions per second would affect which you choose. Here is a very simple alternative. Create an ndb entity with a TextProperty. Serialize the top scores entries using a string such as score_userid. Store them in the text field by joining them with a unique character. When a new score comes in, use get_by_id to retrieve this record (ndb automatically handles memcaching for you). Split it into an array. Split the last element of the array, and check against the new score. If it is less than the score, drop it, and append the new score_userid string to the array. Sort the array, join it, and put() the new TextProperty. If you want you could set up an end of the day cron to scan your scores for the day to check to see if your process was affected by the very small chance that two scores arrived at nearly the same time causing one to overwrite the other. HTH. -stevep
Previous SO high score answer link:
GAE datastore query with filter and sort using objectify

How to store data from generated text fields

Here's an overview of what I want to do.
The program will accept positive and negative integers to do addition, substraction, multiplication, division.
There will be two jars beside each other, while the numbers are being entered balls will drop in the jar.
If the numbers being entered are positive it will drop in one jar and if the numbers are negative it will drop in the other jar. When the calculation is perform the results of the number of balls will remain in the jar.
Also more than two numbers can be calculated at one time.
It's simple but am not sure what path to take.
Can someone guide me on how to this.
I have started but not sure if am on the right track.
Here's what I did so far.
I have two text field with a drop down to choose the type of operation (x, /, -, +).
An "add" button to add more text field if more numbers are required.
But am not sure how to store those numbers and have the numbers drop the amount of balls as they are enter into the text field.
Any help or ideas would be greatful.
Thanks.
Unless I misunderstand what you are trying to do, it looks like you want to have a sort of visual calculator with a variable number of operations per calculation.
While many may argue this, an easy and educational way of doing this would be to create an "Operation" object (class) that holds the entered number and the operation that will be performed (+-*/).
From here there are two approaches that you can take...
The sane approach:
Limit the number of operations to a sane number (ie. 8) and create a statically sized array ( ie. Operation[] ops = new Operation[8]; ) and for every new operation up to the limit, add it to the array.
Once you do this you can either keep a counter of entries or search through the array until you hit an uninitialized index then sort the operations by precedence (+ then - then * then /...) and run the calculation.
The not-so-sane approach:
Unlimited operations! The same thing as previous only using an ArrayList ( ArrayList, java API ) and once you have the total number of entries, do the same as above.
Happy coding ;)

Categories

Resources