I am using the following method to generate an ID number. It starts with the number 0, and compares it to the ID numbers of all existing objects in an array, if it does not equal any of the objects then it should return that ID number and break out of the loop. If it does equal any of the objects it will + 1 and compare 1 to the ID numbers of all objects, until it finds a number that does not match/ is not in use.
However when I run the program, the for loop loops indefinitely, despite being controlled by a boolean which is triggered when all object IDs have been compared and non match. Here is the code:
public int GenerateProductID(){
Boolean NewIDFound = false;
Boolean inUse = false;
int potentialID;
for(potentialID=0;NewIDFound==false;potentialID++){
for(Product productToCompare: this.Products){
if (potentialID==productToCompare.getID()){
{inUse=true;}
}
}
if(inUse!=true){
NewIDFound=true;
return potentialID;
}
}
return potentialID;//Had to return something here although the function will never get here.
}
I have spent a while trying to get to the bottom of this, Java is a new endeavour so apologies in advance if something obvious has been missed. Any help on how to fix this would be greatly appreciated.
inUse means "the current potentialID is in use"; as such, it needs to be reset for each new potentialID.
Related
here i am trying to add a value to the next open position in the array and then return true, and if there isnt any more open positions return false, im a bit lost here as i dont know why it isnt adding the value to the index position on the array.
public boolean add(String item) {
for (int nextPos = 0; nextPos < bag.length; nextPos++) {
if (bag[nextPos] == null) {
item = bag[nextPos];
return true;
}
}
return false;
}
assume i am just filling in the explicit with a random string "x"
what do i have to do to make it add the item to the next slot in the array
update: before i posted this i tried many things in the test cases and no matter what they still returned true regardless if it went past the bag limit
public void testAdd() {
stringBag filledBag = new stringBag(10);
assertNotNull(filledBag);
filledBag.add("next");
filledBag.add("thing");
assertEquals(true, filledBag.add("test"));
stringBag fullBag = new stringBag(3);
fullBag.add("new");
fullBag.add("new");
fullBag.add("new");
fullBag.add("new");
assertEquals(false, fullBag.add("newOne"));
}
so here i assume its reading them as null for the empty slots but its just not assigning them and going straight to true, what is needed to fix this?
update! okay i feel like big dumb, thanks for pointing out that error that i could not find, i guess i was blowing this out of proportion and thought it wa s a bigger problem
this is resolved thanks!
You've made a simple mistake. Assignment places the value on the right side of the = into the variable on the left side. In your case you are storing the contents of bag at nextPos into item (essentially overwriting it to null).
item = bag[nextPos];
What you meant to do was store item into bag at nextPos.
bag[nextPos] = item;
Say, I'm making a simple badugi card game where the Hand is represented by 10 characters in a string. E.g:
2s3h5dQs - 2 of spades, 3 of hearts, 5 of diamonds, Queen of spades
Now, in this badugi card game I want to create two loops where the first loop checks if all the ranks are different(none of them can be the same) and the other loop checks if all the suits are different. If both of these conditions return as true where they all have different ranks and suits, the hand has drawn a badugi(please excuse my lack of terminology where necessary.)
Now, how can I create an efficient loop for such a situation? I was thinking that I could create several if statements as such:
if (hand.charAt(0) != hand.charAt(2) && hand.charAt(0) != hand.charAt(4) && hand.charAt(0) != hand.charAt(6))
if (hand.charAt(2) != hand.charAt(0) && hand.charAt(2) != hand.charAt(4) && hand.charAt(2) != hand.charAt(6))
... and so forth comparing every single index to one another. But this gets tedious and seems very unprofessional. So my question is, how do I write an efficient loop for this scenario? How can I compare/check if there are no matches at these specific index points to one another?
If I haven't explained properly then please let me know.
Please keep in mind, I am not allowed freedom of how to formulate a hand. It has to be in the format above
You are putting your energy into the wrong place.
You do not need to worry about efficiency at all.
Instead, you should worry about creating a clean design (based on reasonable abstractions) and then write code that is super-easy to read and understand.
And your current approach fails both of those ideas; unfortunately completely.
In other words: you do not represent hands and values as characters within a String.
You create a class that abstracts a Card (with its value and face).
And then a "hand" becomes a List / array of such Card objects. And then you can use concepts such as Comparator to compare card values, or you can make use of equals() ...
And even when you wish to keep your (actually over-complex) naive, simple approach of using chars within a string; then you should at least use some kind of looping so that you don't compare charAt(0) against charAt(2); but maybe charAt(i) against charAt(j).
And following your edit and the excellent comment by jsheeran: even when you are forced to deal with this kind of "string notation"; you could still write reasonable code ... that takes such string as input, but transforms them into something that makes more sense.
For example, the Card class constructor could take two chars for suite/value.
But to get you going with your actual question; you could something like:
public boolean isCardDistinctFromAllOtherCards(int indexToCheck) {
for (int i=0; i<cardString.length-1; i+=2) {
if (i == indexToCheck) {
continue;
}
if (cardString.charAt(indexToCheck) == cardString.charAt(i)) {
return false;
}
}
return true;
}
( the above is just an idea how to write down a method that checks that all chars at 0, 2, 4, ... are not matching some index x).
You should really think about your design, like creating Card class etc., but back to the question now, since it's not gonna solve it.
I suggest adding all 4 values to a Set and then checking if size of the Set is 4. You can even shortcut it and while adding this yourSet.add(element) return false then it means there is already that element in the set and they are not unique. That hardly matters here since you only need to add 4 elements, but it may be useful in the future if you work with more elements.
I would advice creating an array with these chars you are referencing just to clean up the fact you are using indices. i.e create a vals array and a suits array.
This would be my suggestion by using a return or break the loop will stop this means when a match is found it wont have to loop through the rest of the elements .. Hope this helps !
private static int check(char[] vals, char[] suits){
int flag;
for(int i=0; i<=vals.length-2;i++){
for(int k=vals.length-1; k<=0;k++){
if(vals[i]==vals[k]){
flag=-1;
return flag;
}
if(suits[i]==suits[k]){
flag=1;
return flag;
}
}
}
return 0;
}
Why not simply iterate over your string and check for same ranks or suits:
public class NewClass {
public static void main(String[] args) {
System.out.println(checkRanks("2s3h5dQs"));
System.out.println(checkSuits("2s3h5dQs"));
}
public static boolean checkRanks(String hand){
List<Character> list = new ArrayList<>();
for (int i = 0; i< hand.length(); i+=2){
if (!list.contains(hand.charAt(i))){
list.add(hand.charAt(i));
}
else{
return false;
}
}
return true;
}
public static boolean checkSuits(String hand){
List<Character> list = new ArrayList<>();
for (int i = 1; i< hand.length(); i+=2){
if (!list.contains(hand.charAt(i))){
list.add(hand.charAt(i));
}
else{
return false;
}
}
return true;
}
}
This is what I have in my method to randomly select a element in my array, however I'm not sure why it isn't working, I feel like I have tried every way of writing it, any ideas.
public static Seat BookSeat(Seat[][] x){
Seat[][] book = new Seat[12][23];
if (x != null){
book = x[(Math.random()*x.length)];
}
return book;
}
The way you explain things makes me think a couple of concepts somehow got crosswired. I am assuming that book is some (2 dimensional) array of Seat objects from which you want to pick a random one. In order to do so, you need to specify a random choice for each dimension of the array:
// this should be declared elsewhere because if it's local to bookSeat it will be lost
// and reinitialized upon each call to bookSeat
Seat[][] book = new Seat[12][23];
// and this is how, after previous declaration, the function will be called
Seat theBookedSeat = bookSeat(book);
// Okay, now we have selected a random seat, mark it as booked, assuming Seat has a
// method called book:
theBookedSeat.book();
// and this is the modified function. Note also that function in Java by convention
// start with a lowercase letter.
public static Seat bookSeat(Seat[][] x){
if (x != null){
// using Random as shown by chm052
Random r = new Random();
// need to pick a random one in each dimension
book = x[r.nextInt(x.length)][r.nextInt(x[0].length)];
}
return book;
}
You should also integrate a test to check whether the selected seat was already booked and repeat the selection:
do {
// need to pick a random one in each dimension
book = x[r.nextInt(x.length)][r.nextInt(x[0].length)];
while (book.isBooked()); // assuming a getter for a boolean indicating
// whether the seat is booked or not
But a full-random selection like this has a couple of disadvantages:
the selection being random, you can repeatedly fall on already booked seats, and the chances that happens increase with the number of already booked seats. But even with few booked seats you could be really unlucky and see the loop spin around tens of times before it hits an unbooked seat.
you should absolutely test whether there are still unbooked seats left before entering the loop or it will spin indefinitely.
Therefore it might be a good idea to implement a smarter selection routine, eg by randomly picking a row and a seat and start searching from there until the first free seat is encountered, but for first steps this one should do just fine.
I hope this is what you wanted to achieve, if not feel free to comment and allow me to correct and adapt.
Floor the number returned by the (Math.random()*x.length) expression.
Math.floor(Math.random()*x.length);
At the moment, you're trying to subscript the array with a floating point number.
The other answer will totally work, but here is another way of doing it using Random.nextInt() if you don't want to have to do all the mathing around:
Random r = new Random();
book = x[r.nextInt(x.length)];
It uses java.util.Random, so make sure you import that if you do this.
I am making a lottery program where I am asking if basically they would like a quick pick ticket. The numbers for their ticket of course would be random since it is a quick pick but the first four numbers range from 0-9 while the fifth number only goes up to 0-4. I am trying to ask them to input a button such as either "1" for no or "2" for yes if they don't want one then it would skip this step. But I am doing the boolean part incorrectly though. Could someone help me out?
Here is an example
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
I still haven't gotten around to making the line of code for the final number of 0-4, just the first four numbers, so I haven't forgotten that.
Your code for case 2 immediately does a return true; which ends the method (I assume this is in a method) right then and there. Your other lines don't get execute at all.
Consider using a switch() statement here, it'll make it easier to read:
switch(QuickPick)
{
case 1:
return false;
case 2:
int n = (int)(Math.random()*9+0); // Why is n here? You don't do anything with it?
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
default:
// Uh oh - someone did something bad maybe just return false?
return false;
}
Also your code for case 2 is definitely wrong, you need to generate a total of five numbers, using bounds 0-9 for the first 4 and 0-4 for the last one. You'll want to use Java's Random to do this (not Math.Random) something like:
Random rand = new Random();
int somethingRandom = rand.nextInt(10);
// Will give you an integer value where 0 < val < 10
// You can call rand.nextInt as many times as you want
To avoid doing your homework for you -- I'll follow the typical CS textbook line and say "Implementation left as an exercise."
The code after return true will not be executed - you need to put that prior to the return statement
Like Marvo said, you dropped a brace in your if.
But you also have faulty logic. I'm not quite sure what the purpose of the method you're in is (that returns a boolean value). But your last few lines will never be reached unless the user types in something like 3 or 42.
Assuming the method is supposed to a) Ask if the user wants a Quick Pick b) Calculate the Quick Pick, if desired c) Return true/false depending on whether the Quick Pick happened or not, you should have:
public boolean doQuickPick()
{
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
}
}
As a separate issue, it'd be much better style to break that into several methods. boolean yesNoPrompt(String message), generateQuickPick(), etc.
Your question is kind of unclear, so I'm afraid I can't be much more help than that. Do post any clarifications / further questions if you have them.
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
In the above copied code from your question, I see that you will be getting compilation errors in your IDE. Your IDE will complain about "Unreachable Code" for the line that is just below the return statement. So, you need to put the return statement at the end of the if block.
this is my first programming course, and i want to make sure i am doing this problem correctly. if you could check over my work it would be greatly appreciated.
Write a method to compute and return the balance for a checking account, given the starting balance and an array of Check objects. You may assume that the Check class already exists and has a method to get the amount from a particular check object called: double getAmount()
The array is not full, and may have gaps in it – make sure you test to see if there is an object there before you try to access it! Make your code work for any length array!
The header for the method is provided for you:
public double computeBalance(double startingBalance, Check[] register) {
int i = 0; // i must be initialized and declared somewhere at least
double total = 0.0;
while ((i >= check.length) && check[i] != null) { // is >= correct? you do i++!
total = (total + getAmount(check[i])); // should you add/compute somewhere
// the given amounts
i++;
}
System.out.println(total);
}
Forget programming for a second. If I told you "Here's the starting balance in your account." and then handed you a bunch of checks and told you to compute the ending balance, how would you do it? Once you understand that, you can start to work on the programming problem.
Some questions:
Where are you tracking the account balance?
What will happen in your loop if one of the slots in register is empty (i.e. null)?
What is this check variable in your loop? Where is it being declared? Is check really what it should be called?
The function is declared as returning double. What are you returning?
Have you tried compiling your code? What happens?
I understand that you are asking for more than for the solution itself but there are obviously better people to guide you. You can use my example as a reference to what others are explaining to you.
public double computeBalance(double startingBalance, Check[] register) {
// let's start off from the starting balance
double total = startingBalance;
// go over all elements starting from 0
for (int i = 0; i < check.length; i++) {
// make sure you did not encounter null element
if (register[i] != null) {
// increase the total by the amount of the Check
total += register[i].getAmount();
}
}
// and finally return the resulting value
return total;
}
The execution will end when you reach a gap. Use an if-statement inside the loop for the null check instead.
If you could run your code through a compiler (which it sounds like you can't, or at least aren't being encouraged to), it would tell you that it has no idea what i, check, or getAmount are.
A method body that doesn't refer to the method parameters is generally missing something -- especially if the parameter declarations were given by your instructor.
Look again at your loop condition. What is the value of i going to be at the beginning?