I made a program that thinks of a number and you have to guess the number.
It is working well, but I got stuck.
First of all, you (the player) has 10 tries in a round. Every wrong guess subtracts 1 from the tries. If you reach 0 you lose.
The variable where the thing stores the randomized number looks like this:
int guess = Integer.parseInt(etGuess.getText().toString());
Of course I have an edittext field with the name etGuess.
So when the player enters the same number twice (for example: 5, then 5 again), the program subtracts 1 then again 1 (so 2) tries.
I'd like to know how can I get the previous value of the guess integer and check whether it was already guessed or not.
I think of something like this:
if ( previous_guess != guess )
Use a HashSet.
Here's how I would do this:
//Declare the variable outside of a function
HashSet<Integer> previousGuesses = new HashSet<Integer>();
//Check if it is already guessed
if (set.contains(guess)) {
//Alert the user that they can't use this.
}
//Adding a variable to it in a function:
set.add(guess);
Make sure to test if it contains before adding it or preforming any of the regular code.
Store all of your previous numbers in an array and then check the array then the player enters a new number.
Related
I want my program to check if the item entered is already in arrayList which is stored within my file ChessList.java, if so produce error and loop back to question else accept number and move on.
Reason being I only want one number to be selected in a row.
Say my program asks for Piece 1, row number and USER ENTERS 5
Then when program loops to piece 2, row number cannot accept 5 again and would produce error.
Therefore, two pieces cannot be contained within in the same row.
Any suggestions how I would go about this? thanks.
I haven't read your code because there's a lot of it, but it just sounds like you want something like
while(true){
int number = getNumber();
if(list.contains(number){
System.out.println("That number is already in the list. Try again");
else{
list.add(number);
break;
}
}
An alternative would be to store it as a Set, which does not store duplicates.
I am trying to write a program containing 3 String ArrayLists, where 1 item may be included in all 3 ArrayLists. However, the output must insure that the randomly selected items are all different. As I work through this issue, I am just using numbers so it will be easier to catch. I have been trying to solve this problem for a few days now, and figure there must be something I am overlooking. Here is the code for the method that must have the fault:
private void generateThree() {
// Find the maximum number the random can be.
index = thirdNumberArray.size();
// Initiate the random function.
Random rand = new Random();
// Generate a random number from 1 to the maximum.
randomInt = rand.nextInt(index);
// Access the item in the ArrayList using the random number as the index.
thirdDrawn = thirdNumberArray.get(randomInt);
// Check that the number is different than any previously set numbers.
while ((thirdDrawn.equals(secondDrawn)) || (thirdDrawn.equals(firstDrawn))) {
randomInt = rand.nextInt(index);
thirdDrawn = thirdNumberArray.get(randomInt);
}
// Set the output.
thirdNumberLabel.setText((thirdDrawn));
// Reset the index.
index = 0;
}
So far, the IF statement I use to check the secondDrawn against the firstDrawn has worked perfectly. But the above code still allows the thirdDrawn to display a duplicate of both the firstDrawn and secondDrawn. I know this problem has to be in my loop logic, but I just can't grasp what it is. I have tried multiple different IF statements, but they didn't solve the whole problem. Can anyone give me some feedback or corrections? Thanks in advance.
Any time you generate a number you want to draw, add it to a HashSet<String>. Then, have your if statement conditional check !myHashset.contains(thirdDrawn).
name = JOptionPane.showInputDialog("What is " + "your name? ");
How do I make this a do while loop so that if the user inputs a number instead of a string it will not move on till a letter is put in. Thanks
Before the loop make a boolean value set to true, and make it so the loop continues until you change the boolean to false. Only set the boolean to false when you get valid input.
You will of course have to check if the number is a int or a string, but exactly how you'd go about doing that will depend on if you want there to be no numbers at all in the string or if it's okay as long as there is at least one character. There are a lot of answers around about that so I'd just Google it.
I need to print out a bar chart, via a call from a method barChartPrinter. I.e. barChartPrinter(5, 6, 2); would print: a vertical column of 5 XX's followed by
a space then a vertical column of 6 XX's and a vertical column of 2 XX's.
The numbers are based on user input, so I'm thinking I need to gather the numbers and store those in an array. And I'm thinking a for loop will be involved,
but I'm not sure how I'd do it.
public class BarChart {
public static void main(String args[]) {
int[] list = new int[4];
Scanner input = new Scanner(System.in);
System.out.println("Enter four integers: ");
for(int i = 0; i < list.length; i++)
list[i] = input.nextInt();
System.out.println();
barChartPrinter(list);
}
public static void barChartPrinter(int[] numbers) {
int max = numbers[0];
for (int i = 0; i < numbers.length; i++)
if(numbers[i] > max)
max = numbers[i];
}
}
This is where I get stuck: defining the method that will print out the bar chart; given the user input values. The method needs to print out in this format, i.e.
barChartPrinter(1, 2, 3, 4) =
For some reason, it won't display how the bar chart should be constructed on here so I'll just describe it:
There would first be a column of XX, then a column of XX (two of these vertically to represent 2), then another column of XX (but this time three of these on top of each other, to represent the number 3) and finally another column of XX * 4 vertically.
Any pointers?
OK, by now I'm sure that you know that it would be trivially easy to create horizontal bar graphs:
2 6 4
**
******
****
Since the print and println methods of the console's PrintStream (the out of System.out) prints things horizontally. The trick for your assignment is how to print this graph vertically. And for that you're going to have to use a little logic. Since this is obviously homework, I'm not going to give you a solution but rather will suggest options.
You know that you'll need to use a loop of some sort to print lines in a row.
One possible solution has you figuring out how many times to loop in advance of the loop by first finding the maximal value held by the array. If you do this, then use a for loop.
Another possible solution you don't find max, but rather just loop til done. Here use a while loop. This would be the option I'd use, and I'd use a boolean variable, say named keepGoing to help tell the while loop when to keep looping and when to stop.
If you go with this latter option, you'll use an int counter in the loop to check what row you're on, and you'll advance this counter inside of the loop.
You will need to nest a for loop inside of your while loop to go through each array item.
You'd use this counter and the array items (in the for loop within the while loop) to see if the String that you will eventually print should have an "* " added to it.
After the inner for loop, you'll print the String you've created.
If no "* " are present (you could call myString.trim().isEmpty()), then keepGoing = false; and the while loop should stop.
Edit: your posted code is a bit off in that it tells the user to enter four numbers but only accepts three. You'll want to fix this.
Edit 2 You state:
Hey, sorry yeah I've sorted the code out. I've coded the way to find the max value within the method. I'm stuck on the step of actually producing the chart now. I know that it will print the XX's each row horizontally, but I'm still stumped as to how I can achieve this- I know it will involve a for loop, but I can't see how I can print the XX's for each column; apologies if I'm missing something obvious
Again, break up your problem by splitting up the big problem into little steps, the smallest you can think of, and then solve each small step. You know that you're going to have to construct a String to be printed, and so you should focus on that, on how to construct this String so that an asterisk is present where need be, and a space is present when the column should show no asterisk. Try to come up with a solution, even a partial solution and post it as an edit to your question, much like how I'm posting this edit to my answer.
I finished a beginner's game program and it works fine, except it's a bit slow when it prompts the user to play again. It is a do...while loop that goes around the entire main method. I want to make it so that the user only needs to type "1" and press enter ONCE rather than twice for the game to replay.
How can I fix this? Also, I'm not sure which part of my program I need to show (if needed), so if you need that, please let me know.
This should work.
if (correctc == 3 && correctp == 3){
System.out.println("\nUser wins! Colour was " + colchoice);
System.out.println("Press 1 to play again with a new combo.");
pagain = myInput.readLine(); // game starts with new combo or ends
}
// User tries guessing again
else{
System.out.println("\nEnter 1 to guess again.");
loop = myInput.readLine();
}
}while("1".equals(loop)); // user continues guessing the same combo
}while("1".equals(pagain)); // new game with new combo
The reason for this is readLine() waits for line to be terminated by "\n" (an enter in this case). You use it twice:
pagain = myInput.readLine();
and then
loop = myInput.readLine();
Isn't "pagain" supposed to be doin what your "loop" is doing? I beileve it is possible to use only one variable to steer both of these loops. For example, you ask to type in "1" to loop again the same set and type in "2" to try with a new set. Then you can get rid of the "loop" variable. It will go out of the inner do-while when it checks that you typed in "2".