I am writing a program in java where the user inputs grades [A, B, C, D, F]. They cannot mention the number of classes so how do I get out of the while loop after they are done.
do {
System.out.println("Enter your grades for all the subjects: ");
String sub1 = input.nextLine();
}
while (<condition>);
I want to understand what kind of <condition> I could use?
TLDR; how about asking them to enter a Q to quit?
Foreword
This answer is highly opinionated, and as such
it's not exhaustive in nature, and therefore not deterministic.
not really in line with SO policy to avoid opinionated answers
I chose to give an opinionated answer in this case because beginner programmers struggle with some of the topics I'll touch on, and hopefully this answer will act as a guide.
The exploration below is intended to give you (the OP) a way to explore solutions about the problem presented and to hopefully expand your understanding on how to attack software design and software development in the future.
Preamble
We start with an assumption (oh the irony) that your original problem-statement probably went something like:
Write a program that accepts grades from a user and then ... do something with it, e.g. compute the overall/average grade of the user
While there are explicit requirements defined by the problem-statement, there are many implicit requirements as well that you, as a software designer, have to make and then use them to create your software.
And because, they are not explicitly defined, they (largely) are up to you to figure out become (aesthetic?) design choices made by you.
So let's just dive right in :-)
Our (first) solution
Let's start with where we're at. We make a few assumptions to pin down our design and therefore our program:
ASSUMPTION: Our user to enter her grades one grade at a time
ASSUMPTION: She wants her result once she's done entering the grades
In the second assumption there's an implicit assumption that she'll be indicating that she's done entering the grades.
In this case our steps could go something like:
DO
INPUT GRADE OR DONE INDICATOR
IF DONE
BREAK OUT OF LOOP
END IF
STORE GRADE
LOOP
CALCULATE AVERAGE
SHOW RESULTS
A different solution
However, we could've made different assumptions:
ASSUMPTION: Our user wants to enter her grades one at a time
ASSUMPTION: She wants to see a running average
ASSUMPTION: She doesn't care about getting done, but perhaps wants to reset the average instead along the way
Now our program may look like:
DO
ASK FOR A GRADE OR RESET
IF RESET
RESET THE AVERAGE
ELSE
ADD GRADE TO CALCULATED AVERAGE
END IF
DISPLAY AVERAGE
LOOP
On the solutions above
As you can see we ended up making plenty of assumptions about the problem to try and pin down what the user wants to experience from our software.
There was another rather blatant assumption that we made which was implicit as well that is that our PROCESS GRADE step is very well defined and the user we are able to simply program that in without the user's input on it.
Even more directions (Choices, Choices, Choices)
And then there are assumptions and directions we could've taken that are completely different from the ones above. Some examples to consider:
She wants something that looks like a calculator
She expects to enter grades in batches
may be of different sizes
may be of IDENTICAL sizes
She expects to give parameters on how to calculate the result (weighted averages?)
May be because she's going to process 100,000,000 grades
Narrowing it down
So, how do we pick which one? Well there are many valid answers to this question as well.
When trying to figure out what design approach you're going to take, consider these mostly nontechnical (common-sense??) factors:
Expectation of the user
Look at how users use similar programs, what do they expect?
When in doubt, ask the users
However, remember the old adage,
"If you make a program that even a fool can use, only a fool will use it"
Ease of programming
Is your approach too complicated for a given problem?
Will you be able to understand your design choices 6 months from now (if you didn't document them -- baaad idea, but still)
Does anybody (including you) care?
Make something, usually if you keep it simple no one will care about the assumptions you made
As you can see, this is highly subjective, and you as a software designer have a lot of power (and per Uncle Ben) therefore a lot of responsibility, to make sane choices for your user and for yourself.
Concluding remarks
All of my thoughts above are meant to help you open your mind to start thinking about set of values and principles for software development. You can create your own, or adopt one of the existing ones and make that your own. I would suggest, at least looking at some software development approaches that are already out there which address some of the topics I touched upon. Even if you don't understand all the technical nitty gritty, just having a 50,000 foot view of them will help you in your endeavors
https://en.wikipedia.org/wiki/Agile_software_development
https://code.tutsplus.com/articles/a-beginners-guide-to-design-patterns--net-12752
And follow the web rabbit hole.
Bon-chance young padawan and happy coding :-)
A common way of doing it is to press crtl-d on mac/unix systems / ctrl-z on windows when you're done.
If that fits your need, you can do it this way:
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter your grades for all the subjects: ");
String text = new String(scanner.nextLine());
//... do what you want here ...
} while (scanner.hasNextLine());
scanner.close();
Related
I am planning on making a note and crosses game in java for my final year college project and I was wondering what different types are AI are there that I can benefit from using in terms of shortening my code etc. Currently, I am planning on using series of if, else if, else statements but my guesses are that it will require large amount of code because I will need to check for all the possibilities for example, when checking for wins, I would do something like.
if(button1.getText().equals(button2.getText()) && button2.getText().equals(button3.getText()) && button1.getText().equals("X"))
{
wining statement.....
}
.....
.....
.....
repeat for all the possibilities of winning,
Let's see what you've got. Probably this is a duplicate of a bunch of questions though.
It seems you do not have the data structures right yet. I would go with a two dimensional array (or a one dimensional with accessor methods to look like a 2D array), so the individual (named) buttons is a bad idea imho.
After that you should check the tic-tac-toe related questions, I guess you will find some inspiration and the discussion part of your paper will have more voices, opinions. There are many ways to solve this, playing the game a few times you will realize the first user should put its sign to the middle and after that there are not many choices. If you prefer to find these rules automatically, you can use backtracking, alpa-beta cutting, neural network, almost anything that is AI related.
Good luck to this task!
So I am trying to design an algorithm to calculate the specific items I can buy, based on the amount of money I have, to get the most value of the purchase, given that each item has specific value. So my plan was to use nested if else statements etc... But that is extremely inefficient. Any input?
I am not asking for anyone to solve this for me. I am simply asking if this way is one of the least efficient but still successful way of doing it.
It sounds like you're trying to implement the Knapsack problem.
You can read about it here:
http://en.wikipedia.org/wiki/Knapsack_problem
I dont completely understand the question but, depending on your conditions a switch block could be better, but its actual performance increase is little
ref: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I was asked this in WRITTEN form through a recruiter, with the previous question being string related, and the previous one being about Inversion of Control:
How would you find the second largest element in an array?
Being a Project manager who has is self teaching/learning JAVA, my response was:
How is large defined (integers? parsing of: strings/objects? ) How large is the array? Bubble sort , then return the second to last index. Temporarily store the largest and second to largest variable, sort through the array, replacing the appropriate variables, then return the second largest variable. There are many ways, however to develop an appropriate function that isn’t expensive would require more information. If the range is very wide, make several lean methods, measure the array length, and apply the appropriate method on the array.
Is this a valid response to the question, and if not, what do you think it needs improvement on? I'm asking this because of the extreme gap presented in the common recruitment atmosphere, and am having difficult understanding the actual intended purpose of similar structured questions, and need your feedback to understand what/how to approach/reply.
UPDATE I received notification that they typically see code, but provided no parameters or guidelines, and replied with this:
I can not provide a codified answer, not knowing at least the first two pieces of information. The first will allow for parsing, as numbers are sorted universally, while strings, objects, and others are parsed subjectively. The second part, dealing with the array length, and whether or not it is static, is definitely relavent as a developer, as expensive code (whether in computation time facing the user, or hardware costs to the client) can be costly. The question is worded poorly for an exact technical response, especially given that it is in written format, where there is no feedback. I am merely typing my considerations as a reply, the same as if it were asked in person. The context I am given from the previous questions is that they are looking for someone who understands IoC practices (bullet 3) and would be parsing Strings (given bullet 2) in potentially a transaction (try/catch) situation (bullet 4) and then find (current issue). If the questionnaire's purpose is to see how I approach a problem, then my response is valid. If they would like further clarification, I would be happy to accomodate, but if they are requiring a codified answer AND unwilling to provide the necessary context, then I am unwilling to work with them, as it would highlight there misunderstanding of how to interact with external customers, who DO need guidance when one "simple" question is asked, but other pieces of information are needed to best accommodate, the central reason behind any business seeking outside specialized help. I hope this response in not read in a harsh tone, as my cadence when replying out loud is quite the opposite, as further information is required, including if sole development in JAVA is within the scope of this job, as I am skilled in JS and Python as well, and this was not discussed yesterday. Hopefully you and your client can understand that with the recruiter method, a layer of abstraction can be beneficial in many areas, but in situations like this, it can hinder and cloud perceptions without direct communication and feedback. Please feel free to provide this in addition to my answer.
and received acclaim for this reply. Thank you for your help, as I am really trying to get a programming job, but have no prior formal experience and this guidance really helps.
In this case, I think the interviewer really wants to know in order to find 2nd largest element, does one have to sort the entire array(and pick the second element) or is there any better approach?
The answer is you don't have to sort the entire array in order to find top k elements. Sorting will take O(nlgn) time whereas finding top k items will take only O(nlogk).
You can explain the answer using simple example. If you have to find 2nd largest card in 100 cards with numbers ranging some low to high. The cards are not sorted. To find 2nd largest card, all of you have to do is hold top 2 cards that you have seen so far in your hand. As you pick new cards, see if it is larger than the one in your hand, if so replace the new largest with the smallest in hand. At the end of this process, you will end up holding top 2 cards.
EDIT: Like others said, bubble sort has worst runtime O(n^2). For fun, Check out President Obama's answer to sorting interview question. http://www.youtube.com/watch?v=k4RRi_ntQc8
The most efficient to do the needed task is obvious: iterate once on the array and looking for the "largest" element, all the while storing also the previous "largest" element. At the end of the array, your previous "largest" element is the one your method needs to return.
To formulate your answer, I see 2 choices:
Beginning your answer by "Assuming the array contains int elements..." or something approaching.
Using an undefined isLargest() or isLarger() method and explain that the purpose of the method is to check if the current element is largest currently examined, whatever it means.
This is pretty subjective, but frankly I agree with your question-about-the-question -- they should have defined what it is your array contains.
What you could have done is written something like "Assuming the elements in the array are all integers, here's how I'd do it" and then give your answer with that assumption.
I'd follow the same steps with your other requests for additional info -- make an assumption, declare your assumption, then proceed with that assumption in mind.
Seems valid - I just fear they wanted CODE. I think maybe you should have just assumed integers and written something IN ADDITION to what you said.
My initial gut reaction would be "Modified Merge Sort", implemented using a ForkJoinPool. It's still O(n log[n]), but the actual runtime would be faster than a serial implementation.
You may ask why not quicksort, and it's because worst case for quicksort is O(n^2), which would be bad for an extremely large dataset. Modified Merge Sort has more predictable performance and a better worst case scenario O(n log[n])
I am developing a financial manager in my freetime with Java and Swing GUI. When the user adds a new entry, he is prompted to fill in: Moneyamount, Date, Comment and Section (e.g. Car, Salary, Computer, Food,...)
The sections are created "on the fly". When the user enters a new section, it will be added to the section-jcombobox for further selection. The other point is, that the comments could be in different languages. So the list of hard coded words and synonyms would be enormous.
So, my question is, is it possible to analyse the comment (e.g. "Fuel", "Car service", "Lunch at **") and preselect a fitting Section.
My first thought was, do it with a neural network and learn from the input, if the user selects another section.
But my problem is, I don´t know how to start at all. I tried "encog" with Eclipse and did some tutorials (XOR,...). But all of them are only using doubles as in/output.
Anyone could give me a hint how to start or any other possible solution for this?
Here is a runable JAR (current development state, requires Java7) and the Sourceforge Page
Forget about neural networks. This is a highly technical and specialized field of artificial intelligence, which is probably not suitable for your problem, and requires a solid expertise. Besides, there is a lot of simpler and better solutions for your problem.
First obvious solution, build a list of words and synonyms for all your sections and parse for these synonyms. You can then collect comments online for synonyms analysis, or use parse comments/sections provided by your users to statistically detect relations between words, etc...
There is an infinite number of possible solutions, ranging from the simplest to the most overkill. Now you need to define if this feature of your system is critical (prefilling? probably not, then)... and what any development effort will bring you. One hour of work could bring you a 80% satisfying feature, while aiming for 90% would cost one week of work. Is it really worth it?
Go for the simplest solution and tackle the real challenge of any dev project: delivering. Once your app is delivered, then you can always go back and improve as needed.
String myString = new String(paramInput);
if(myString.contains("FUEL")){
//do the fuel functionality
}
In a simple app, if you will be having only some specific sections in your application then you can get string from comments and check it if it contains some keywords and then according to it change the value of Section.
If you have a lot of categories, I would use something like Apache Lucene where you could index all the categories with their name's and potential keywords/phrases that might appear in a users description. Then you could simply run the description through Lucene and use the top matched category as a "best guess".
P.S. Neural Network inputs and outputs will always be doubles or floats with a value between 0 and 1. As for how to implement String matching I wouldn't even know where to start.
It seems to me that following will do:
hard word statistics
maybe a stemming class (English/Spanish) which reduce a word like "lunches" to "lunch".
a list of most frequent non-words (the, at, a, for, ...)
The best fit is a linear problem, so theoretical fit for a neural net, but why not take immediately the numerical best fit.
A machine learning algorithm such as an Artificial Neural Network doesn't seem like the best solution here. ANNs can be used for multi-class classification (i.e. 'to which of the provided pre-trained classes does the input represent?' not just 'does the input represent an X?') which fits your use case. The problem is that they are supervised learning methods and as such you need to provide a list of pairs of keywords and classes (Sections) that spans every possible input that your users will provide. This is impossible and in practice ANNs are re-trained when more data is available to produce better results and create a more accurate decision boundary / representation of the function that maps the inputs to outputs. This also assumes that you know all possible classes before you start and each of those classes has training input values that you provide.
The issue is that the input to your ANN (a list of characters or a numerical hash of the string) provides no context by which to classify. There's no higher level information provided that describes the word's meaning. This means that a different word that hashes to a numerically close value can be misclassified if there was insufficient training data.
(As maclema said, the output from an ANN will always be floats with each value representing proximity to a class - or a class with a level of uncertainty.)
A better solution would be to employ some kind of word-relation or synonym graph. A Bag of words model might be useful here.
Edit: In light of your comment that you don't know the Sections before hand,
an easy solution to program would be to provide a list of keywords in a file that gets updated as people use the program. Simply storing a mapping of provided comments -> Sections, which you will already have in your database, would allow you to filter out non-keywords (and, or, the, ...). One option is to then find a list of each Section that the typed keywords belong to and suggest multiple Sections and let the user pick one. The feedback that you get from user selections would enable improvements of suggestions in the future. Another would be to calculate a Bayesian probability - the probability that this word belongs to Section X given the previous stored mappings - for all keywords and Sections and either take the modal Section or normalise over each unique keyword and take the mean. Calculations of probabilities will need to be updated as you gather more information ofcourse, perhaps this could be done with every new addition in a background thread.
I'm trying to add to the code for a single layer neural network which takes a bitmap as input and has 26 outputs for the likelihood of each letter in the alphabet.
The first question I have is regarding the single hidden layer that is being added. Am I correct in thinking that the hidden layer will have it's own set of output values and weights only? It doesn't need to have it's own bias'?
Can I also confirm that I'm thinking about the feedforward aspect correctly? Here's some pseudocode:
// input => hidden
for j in hiddenOutput.length:
sum=inputs*hiddenWeights
hiddenOutput[j] = activationFunction(sum)
// hidden => output
for j in output.length:
sum=hiddenOutputs*weights
output[j] = activationFunction(sum)
Assuming that is correct, would the training be something like this?
def train(input[], desired[]):
iterate through output and determine errors[]
update weights & bias accordingly
iterate through hiddenOutput and determine hiddenErrors[]
update hiddenWeights & (same bias?) accordingly
Thanks in advance for any help, I've read so many examples and tutorials and I'm still having trouble determining how to do everything correctly.
Dylan, this is probably long after your homework assignment was due, but I do have a few thoughts about what you've posted.
Make the hidden layer much bigger than the size of the input bitmaps.
You should have different weights and biases from input -> hidden than from hidden -> output.
Spend a lot of time on your error function (discriminator).
Understand that neural nets have a tendency to get quickly locked in to a set of weights (usually incorrect). You'll need to start over and train in a different order.
The thing I learned about neural nets is that you never know why they're working (or not working). That alone is reason to keep it out of the realms of medicine and finance.
you might want to read http://www.ai-junkie.com/ann/evolved/nnt1.html . there it mentions exactly something about what you are doing. It also provided code along with a (mostly) simple explanation of how it learns. Although the learning aspect is completely different from feed forward this should hopefully give you some ideas about the nature of NN.
It is my belief that even the hidden and output layers should have a bias.
Also NN can be tricky, try first identifying only 1 letter. Getting a consistent high/low signal from only a single output. Then try to keep that signal with different variations of the same letter. Then you can progress and add more. You might do that by teaching 26 different networks that give an output only on a match. Or maybe you make it as one large NN with 26 outputs. Two different approaches.
As far as the use of bias terms is concerned I found the section Why use a bias/threshold? in the comp.ai.neural-nets FAQ very useful. I highly recommend reading that FAQ.