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.
Related
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).
I have a class that "bans" a player, but I don't want that player to be banned if his name is within a string array. I could loop through the length of the array and use booleans, but there has to be an easier way? I saw something that said just put if a condition is met, put return; and it'll stop all code running below that if statement.
Edit: Thanks for all the help! You were all helpful, even if you're one of the people that downvoted this, which is 4 people at least.
You could make a method that checks if the player is in the array of Strings and yes if you use return in a void method the method will just end.
For example
public void returnUsage(int n)
{
if(n==1)
{
return;
}
System.out.println("n doesn't equal 1.");
}
But it would probably be best to use an if and else to skip the code you don't want to run if the condition is not met. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
An array is the wrong data structure for this task. Add the players to a Set<> allowedPlayers = new HashSet<String>() then use if(allowedPlayers.contains(name)) return; to conditionally exit the method based on whether the name of the player is in the set. The set will remain fast when the number of names gets large. With an array scanning the array will be slow when the array is big.
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.
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.
What I'm trying to do is set up 14 arrays that will be of both type string and double to be able to accept input into the first index, and then the next time that the user enters in their information I don't want to add that information into an index that's already been given a value, but I do want to add that new information into the next index of that array. Do I just ++Array[index]? I'm also trying to set up this program to allow the user to be able to access 1 of 3 different IFstatements at a time to input values. If they enter input into an Array in IFstatement1, and then leave IFstatement1, go to IFstatement2 to input something, and then want to come back to IFstatement1 and input data into Arrays there, will the program know to add the newest user inputs into the next index in the array by using the ++Array[index] indicator, or do I have to do something else? How do I accomplish this?
Try looking into the ArrayList object this should work for what you are looking for and it has a nice .add() function to add to the end of the list.
List<String> l1 = new ArrayList<String>();
l1.add("String");
l1.add("Another");
for (String str : l1) {
System.out.println(str);
}
This will add the strings and provide you the iterator.
If you want another with Doubles just change for or you can have one without generics that will just hold objects <> remove them. Then your for loop would traverse the objects instead.
You can't use ++Array[index] to add an element to an array in Java. As in other statically typed languages, array's are given a size when they are created and can't contain more values then their initial size. So for instance int numbers[10]; can hold 10 integer values. If you want to set the values in that array use something like this:
int numbers[10];
for (int i = 0; i < 10; i++) {
numbers[i] = 1 + 1;
}
With regards to the user input you describe, you would need to use some form of looping, maybe a while loop?