Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am beginner in java. Please provide a sample program in Java to play a number-guessing game. The game works as follows:
The user chooses a number in his mind and types “ready” to indicate to the computer that he is ready to
begin playing.
The computer asks a series of questions to arrive at the number the user has in mind. The user can only
respond with “higher”, “lower” or “yes”.
The game ends when the user responds with “yes” or “end”.
Example:
User chooses number 40 in his mind.
Computer: Is the number 30?
User: higher
Computer: Is the number 50?
User: lower
Computer: Is the number 35?
User: higher
Computer: Is the number 40?
User: yes
Firstly : You shouldn't ask for sample code without any of your own code - that's likely why this is being downvoted.
Moving on, you should decide how you want your program to guess. For example, a bisection algorithm might be useful for you here. You'd need to set some initial code which differed, in order to bound the person's number.
Eg: (pseudo-code)
int guessLower=0;
int guessUpper=1000000;
int myGuess=10;
// Ask user to pick number
// Ask user if number is == guess
// If yes, finish.
// If the answer is higher than the guess, change guessLower to the value of guess, and change guess to halfway between guess and guessUpper.
// If the answer is lower, do the opposite (guessUpper = myGuess; myGuess = (guessLower + myGuess)/2;
// Repeat until finished
This (~)code won't work if the value the person makes up isn't within the limits you set - so consider asking first if it is higher than guessLower, and lower than guessUpper. If not, try moving the markers by some amount. More complicated algorithms for searching can be easily imagined, and you should be careful about the differences between integers and doubles etc.
On a side note, for comparing strings, you should look up using equals(...), eg input.equals("higher");. Don't use the C++ == for comparing the values of strings, I anticipate this might be a problem you'll hit...
I won't write or provide a program for you, this is pretty basic.
A few bits to get you started:
You need to use a Scanner object to read in from the keyboard. This question should cover that part pretty well: Getting Keyboard Input
You also need to understand booleans. Click here for that.
And finally you should probably learn about "relational operators," like > is greater than, < is less than, etc. Check here for that.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
I saw this question online and was wondering how to design an efficient ADT and data structure for a raffle like problem.
Sashu is an Instagram influencer for Nike and is doing a giveaway of the new Air Jordans! She posted on Instagram revealing this and asking everyone to comment on the post in order to enter the raffle! Instagram has limited the number of times each individual can comment on a post to 50 as each comment represents a single entry for a giveaway. At the end of one week, Sashu announces that she will randomly select 10 individuals to win the giveaway and the shoes!
You are tasked with designing a system (a digital bowl) from which Sashu can draw the names, specifically implementing the following methods:
addEntry(String username): insert a new entry with the given username into the digital bowl (people can comment multiple times, duplicates will be allowed)
withdrawUser(String username): withdraw every entry with the given username from the digital bowl (if a winner is already selected, they must not be chosen again)
drawWinner(): randomly select a winner from the digital bowl for the giveaway and withdraw all entries with the same name from the bowl. The probability of a specific name being selected must remain proportional to the number of entries from the same username in the digital bowl.
My solution:
Because I want this design to run in O(n), I was thinking of creating a hashmap so that every key represents the username and the count represents the value. To maintain the probability of a specific name being selected to remain proportional to the number of entries from the same username, I will be using another data structure, an arraylist to store the usernames and add it to the end of the list each time with duplicates. Since I need to withdrawn an entry after selecting a winner, I will need to search the username in the list. However, the worst case might take O(n) if the username is at the end of the list. How might I prevent the worst case and let the runtime be constant and not linear? Thank you
The setup of this problem more or less necessitates that at least one function be slower than the others. Your solution is already valid in terms of time complexity, given that you can add elements to an ArrayList in amortized O(1) time. But to answer your question, you can move the tradeoff elsewhere.
Read this answer regarding selecting elements with weighted probabilities. If you want an even bigger hint, keep reading.
You do not need a second data structure beyond your HashMap. You can maintain a count of total entries, say numEntries. Then write drawWinner() to do the following:
create a random number, say randNum, from 0 to numEntries
iterate through the keys (the usernames) of the HashMap
for each username, decrement randNum by the associated value
if randNum hits 0, then that user has been chosen
This maintains the proper weights of each user while simplifying your program. This makes withdrawUser() O(1) in exchange for making drawWinner() O(n) in the number of users. As long as the number of users and their respective weights are not known beforehand (which I assume is the case given there is an addEntry() function), this is essentially the most reasonable way to achieve what you want.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I wrote a simple, low-level randomizer that creates a character for a board game that my friends and I play. However, after writing it, I realized that I also needed an easy way to rerun the program in order to generate a new random character. Currently, I must close the program and then rerun it in order to generate a new character. Is there any simple way to do this? Please note that I am a rather intermediate coder.
I've searched the Web and most of the solutions that I found require creating a GUI. That is something I would prefer not to do. I've also tried using a while loop as a solution but I haven't found a way to pause the program until a button is pressed.
Anything simple would be appreciated. If I must do something more complex, like creating a GUI, I am prepared to learn how to.
There are two solutions to your problem. Using a for loop and using a while loop.
A for loop will run a block of code x amount of times. e.g.
System.out.println("How many characters would you like? ");
Scanner scanner = new Scanner(System.in);
int result = scanner.nextInt();
for (int i = 0; i < result; i++) {
// Code to give user a character runs "result" amount of times
}
A while loop will run indefinitely until a condition is met. e.g.
boolean anotherCharacter = true;
while (anotherCharacter) {
// Code to give user a character runs until "anotherCharacter" is false
System.out.println("Would you like another character? (yes/no) ");
Scanner scanner = new Scanner(System.in);
String result = scanner.next();
if (result.equalsIgnoreCase("no")) {
anotherCharacter = false;
}
}
In your situation, the best option to choose depends on whether or not you know exactly how many characters you want at the start of the game. If so, I would recommend the for loop. However, if you do not know the number of characters at the start of the game, I would recommend the while loop.
Simplest solution I see is with your while loop, to ask between characters « do you wish to continue » with a yes/no answer. This way your program would wait between executions.
You could then wrap your character making logic inside that while loop.
Googling for « java input » would help you there.
I believe you wanted to execute a code until a specific key is pressed(and not a button which will only be available in the case of a GUI). This wont be possible unless you implement it using native libraries. You can go through JNI or JNA docs to accomplish this. It would be much simpler to use GUI's though, and will be platform independent unlike in the case of native libraries.
JnativeHook can be used to implement the functionality that you are looking for using native libraries.
I'm currently coding a clock app in java for android, and I want to implement a snooze function where when the alarm goes off, a random math problem would appear on the screen. The user would have to successfully answer the math problem before the alarm would snooze/turn off. I'm completely lost on how I would implement this feature. Any guidance on how i'd implement this would be greatly appreciated. Thanks.
First, I'd like to say that what ever I'm about to tell you is the way I would do it, since you did not specify any way specifically you would like to do it. I am no Java expert, but you could probably generate two random integers from a certain range (maybe something like 2 to 11) using Math.random. Try looking at this question for info on how to do that: How do I generate random integers within a specific range in Java? or Math.random() explained Then maybe generate a random number from 1 to 4 where 1 is addition, 2 is subtraction, 3 is multiplication, and 4 is addition. Then you could have an if statement for subtraction and division that checks if the first number is greater than the second number. Also, you could have another if statement for division checking if the division statement ends up with a whole number. Then you could have a final if statement checking if the user typed in the right answer. If you want you could make little alerts for if they got it wrong or right. As for the snooze function, you could just make a property that adds a certain amount of minutes to your method for the alarm. Also, I'd like to say that I like your idea for the math problems!
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();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm currently using Java to code a program that can have conversations and solve problems.
So far, the program can only have conversations. The solving problems is still in process.
The program is capable of learning, however, it's how I made that happen that gives me doubts.
The way my program learns new words is it stores them in a TreeView menu as branches.
Each branch (word) has sub-branches that give the word meaning.
Each sub-branch has sort of like different tags to differentiate the relation to the main branch.
For example, if I teach it the word Hello and type Hello>>Hi, it then saves Hi as a sub-branch in the main branch Hello, but in the form of =s=Hi=s= to tell the program it's a synonym of Hello, so it can use Hi instead of Hello. More synonyms can be added.
Though if you type, for example, Hello<>Greeting, it stores the branch Greeting in Hello in the form of =m=Greeting=m=. To show that Hello is a type if greeting.
There is more, but too much to explain.
Just my cheap attempt on A.I.
Can this class as a program learning? Or have I got a long way to go?
As per definition of AI:- It's the capacity to perform operations analogous to learning and decision making in humans.
Your program do seems to learn the new words and make decision on what type of word it is i.e. Hello, Hi -->Greeting
But more than learning, how you control its learning will be AI. For example if I use a bad word for greeting, it should not learn it. Controlled learning and decision-making do make your program a true AI program.
You have actually started to learn AI. And this what you do is called giving ground terms manually for the machine. But AI is something that the system learns by itself. For example, now you have taught that hi is a way of greeting, if some other user greets it, it must greet him too. And yes you will be writing logic for that too. You cannot fully achieve AI such that the computer learns itself without writing any logic for it (only fictional characters like Jarvis can do so).
To be frank I am not deep into machine learning and AI. But to my perception, I think some sort of implementation which involves human like thinking would be better. For example, try to implement a chess game. In that you have back tracking. You can get a better understanding. Properties of each coin and their power is what you give as ground terms(base knowledge). And based on the moves of User, system must analyze future moves and predict user's view and backtrack to make its move.
Not sure whether I answered your question, but you seem to be doing cool stuff, thumbs up for you, move on and develop cool and small scale AI systems first which involves lot of computation and Algorithm stuffs.