Im not getting white this iteration doesent work? - java

When I output this album1.findSongInAlbum() method, no matter what I input I get "not working" or if I enter right name, I get album song found, and again also Not working.
public boolean findSongInAlbum(String songName) {
for (int i = 0; i < this.albumContainingListOfSongs.size(); i++) {
if (songName.equals(albumContainingListOfSongs.get(i).getTitle1())) {
System.out.println("Album song found: " + albumContainingListOfSongs.get(i).toString());
} else if (!songName.equals(albumContainingListOfSongs.get(i).getTitle1())) {
System.out.println("Not workin");
return false;
}
}
return true;
}
output is supposed to be one or another, either found song, or not found song, but never both.

Your logic is wrong.
If you find a match, you should return true immediately.
If you don't find a match, you should stay in the loop, and not return false. Only return false after the loop is done.
This should work:
public boolean findSongInAlbum(String songName) {
for (int i = 0; i < this.albumContainingListOfSongs.size(); i++) {
if (songName.equals(albumContainingListOfSongs.get(i).getTitle1())) {
System.out.println("Album song found: " + albumContainingListOfSongs.get(i).toString());
return true;
}
}
System.out.println("Album song not found");
return false;
}

Related

Java expects an "AnnotationName" after a method declaration

I am coding a game in Java, and must create a method inside an enum type that returns whether the player may fill a bottle with liquid or not. The method checks whether the player's inventory contains a bottle, and whether the player is near a liquid.
In the method declaration, I am getting an error that says I need to put an "AnnotationName" after it. I do not know what an "AnnotationName" is, and on all the other methods I have created in the file there are no such errors.
There is also another error at the bottom of the enum on the closing bracket. It says "Please insert '}' to complete ClassBody". I have checked all the curly brackets in the file and they all have matches. I think this error must be tied to the above "AnnotationName" error. I have included the method below, as well as the enum type the method is a part of.
The method by itself:
//the problematic method
#Override
public boolean isAvailable() {
//create var
boolean bottleInInventory = false;
//loop thru junk sublist
for (int i = 0; i < Data.player.sizeOfSubList(0); i++) {
//if current item is a Bottle, bottleInInventory = true; otherwise do nothing
if (Data.player.getItem(ItemType.JUNK, i).getClass() == Bottle.class) {
//set var to true
bottleInInventory = true;
}
//repeat loop until a Bottle is found (or not found)
}
//check if player is near a liquid AND if they have a Bottle in their inventory
//if they satisfy both conditions, return true
try {
if (Data.nearLiquid.get(0) != null && bottleInInventory) { //if index 0 has nothing in it, there must'nt be anything in the other indexes either.
return true;
}
} catch (IndexOutOfBoundsException e) { //if the player is not near any liquids this will happen during the above if statement.
return false;
}
return false; //if player is near a liquid and not in possesion of a Bottle
}
The whole enum:
FILL_BOTTLE("Fill Bottle") {
//this method is not complete
#Override
public void opCode() {
boolean multipleBottles; //if there is more than one bottle or not
ArrayList<Bottle> bottlesInInventory = new ArrayList<Bottle>(); //output of loop
Item currentItem; //used only inside loop
for (int i = 0; i < Data.player.sizeOfSubList(0); i++) { //loop counts how many bottles you have
currentItem = Data.player.getItem(ItemType.JUNK, i);
if (currentItem.getClass() == Bottle.class) {
bottlesInInventory.add((Bottle) currentItem); /* currentItem will always be assigned to a Bottle here,
* but we still need to cast because the
} * variable type is an Item. */
}
//multipleBottles is set to true if the bottlesInInventory list has more than one item in it
if (bottlesInInventory.size() > 1) {
multipleBottles = true;
}
System.out.println("You are currently able to fill your bottle with " + Data.nearLiquid.size() + " liquids near you");
System.out.println();
System.out.println("Here they are:");
for (int i = 0; i < Data.nearLiquid.size(); i++) {
System.out.println((i + 1) + ") " + Data.nearLiquid.get(i).getName());
}
int liquid = Data.intPrompt("Which liquid would you like to fill your bottle with? ");
}
//the problematic method
#Override
public boolean isAvailable() {
//create var
boolean bottleInInventory = false;
//loop thru junk sublist
for (int i = 0; i < Data.player.sizeOfSubList(0); i++) {
//if current item is a Bottle, bottleInInventory = true; otherwise do nothing
if (Data.player.getItem(ItemType.JUNK, i).getClass() == Bottle.class) {
//set var to true
bottleInInventory = true;
}
//repeat loop until a Bottle is found (or not found)
}
//check if player is near a liquid AND if they have a Bottle in their inventory
//if they satisfy both conditions, return true
try {
if (Data.nearLiquid.get(0) != null && bottleInInventory) { //if index 0 has nothing in it, there must'nt be anything in the other indexes either.
return true;
}
} catch (IndexOutOfBoundsException e) { //if the player is not near any liquids this will happen during the above if statement.
return false;
}
return false; //if player is near a liquid and not in possesion of a Bottle
}
},
I've tried adding curly brackets, annotations (#Override), and researched on AnnotationNames but not had any luck. I can't find any documentation on what an AnnotationName is, and the curly brackets and extra annotations just created more errors.
Edit:
Here is a link to the entire file as well as a link to the github repo with my code.
Option.java
Jump The Volcano

FRQ High Scores Part B: I'm getting a "missing a return statement" when the returns are in the for loop? Shouldn't the returns be reached?

I'm a high schooler in apcs and I'm trying to practice these for the test. The code should return whether a new object was created. Also, the moveUp method doesn't allow me to call it using the scoreboard list (e.g. "scoreboard.move(int x)". Please explain why I'm wrong, but don't solve it.
public boolean newScore(String name, int score)
{
/* Implement your answer to part (b) here */
for (int ind = 0; ind < scoreboard.size(); ind++) {
Player player = scoreboard.get(ind);
if (player.getName().equalsIgnoreCase(name)) {
player.updateScore(score);
moveUp(scoreboard.indexOf(player));
return true;
} else {
Player p = new Player(name, score);
scoreboard.add(p);
p.updateScore(score);
moveUp(scoreboard.indexOf(p));
return false;
}
}
}

my compiler gives me this error yet what is saying is there?

public void String printRentalList(){
for(int v = 0; v < numOfRoomsHR; v++){
System.out.println(theRooms[v].toString);
}
}
public void addReservation(Room a){
if (numOfRoomsHR < theRooms.legnth){
theRooms[numOfRoomsHR] = a;
numofRoomsHR++;
} else {
System.out.println("Can not add anymore rooms to the hotel");
}
}
public void String findReservation(int l){
boolean flag = false;
for(int i = 0; i < numOfRoomsHR && !flag; i++){
if(theRooms[i] == l){
flag = true;
System.out.println("Reservation found for room number:" + l + "\n" + theRooms[i].toString);
} else {
System.out.println("Reservation not found for room number:" + l);
}
}
}
I was working through my project and compile checking to see if I did anything wrong through out the project I got this error:
error: '(' expected
For the line printRentalList() and the PrintList() yet the ( is there. any suggestions ?
It is probably the .toString on this line:
System.out.println("Reservation found for room number:" + l + "\n" + theRooms[i].toString);
Java would expect the ( after toString, as toString() is a method. I also noticed, as rgettman said: you have multiple return types with void and String. You do need to pick one and it seems, at least for the second function it should be void since you do not appear to be returning anything.

Java method running very slowly on first run only (Android)

I have found that my method called checkForErrors takes around 80x longer to run on the first execution only, and I can't seem to figure out why.
D/guess: adhl
D/checkerror: checking for errors took 4760743ns // first run
D/validity: checking guess validity took 7141114ns
D/guess: agkl
D/checkerror: checking for errors took 61035ns // every other run takes around this long
D/validity: checking guess validity took 732422ns
I have looked through the code and I don't see anything that would take longer on the first run only so I'm stumped.
Button on click listener:
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Guess = guess_txt.getText().toString();
Log.d("guess", Guess);
if(checkGuessValidity(Guess)){ // <--
submitValidGuess(Guess);
int bulls = game.getBullsAndHits()[0];
int hits = game.getBullsAndHits()[1];
if(!game.gameWon) //if game is not won, submit the guess with bulls and hits
guessSubmittedListener.guessSubmitted(Guess, bulls, hits);
else //if game is won, call gameWon() method
gameEnd();
}
if((game.getCurrentTry() > game.getMaxTries()) && (!Guess.equals(game.getHiddenWord()))) gameEnd(); //if user is out of tries, call gameLost method
triesLeft.setText("Tries Left: " + (game.getMaxTries() - game.getCurrentTry() + 1)); //update tries left on main fragment
guess_txt.setText("");
}
});
checkGuessValidity:
public boolean checkGuessValidity(String Guess){
long start = System.nanoTime();
long start2 = System.nanoTime();
ErrorList Status = checkForErrors(Guess); // <--
long end2 = System.nanoTime();
Log.d("checkerror", "checking for errors took " + (end2 - start2) + "ns");
. . . more code . . .
checkForErrors:
public ErrorList checkForErrors(String Guess){
if(Guess.length() != game.getHiddenWordLength()) return ErrorList.Wrong_Length;
else if(!isValidInput(Guess)) return ErrorList.Invalid_Characters;
else if(!isIsogram(Guess)) return ErrorList.Not_Isogram;
else if(!isLowercase(Guess)) return ErrorList.Not_Lowercase;
else return ErrorList.OK;
}
isValidInput, isIsogram and isLowercase:
public boolean isIsogram(String Guess){
Map<Character, Boolean> map = new HashMap();
for(int i = 0; i < Guess.length(); i++){
if(map.get(Guess.charAt(i)) == null) //if the value for the key (character) is null (has not been changed since map initialization)
map.put(Guess.charAt(i), true); //then set it to true (indicating that it has been seen)
else { //else (if the value at the character HAS been changed since initialization, ie. it has been seen)
Log.d("Character repeated", "" + Guess.charAt(i));
return false; //return false
}
}
return true; //if loop completes no duplicates were found and guess is an isogram
}
public boolean isLowercase(String Guess){
if(Guess.equals(Guess.toLowerCase())) return true;
else return false;
}
public boolean isValidInput(String Guess){
char[] chars = Guess.toCharArray();
for(int i = 0; i < chars.length; i++){
if(!isLatinLetter(chars[i])) return false;
}
return true;
}
public static boolean isLatinLetter(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
It doesn't seem like any of the methods should be impacted by when they are run, so I don't know why it takes extra long on the first execution. I'm still a beginner to programming so please excuse any poor formatting or horribly optimized code :p .
edit: CPU usage graph: https://prnt.sc/ftjokq

How do I check if a class' return of a method equals null?

In my program, I have a while loop that will display a list of shops and asks for an input, which corresponds with the shop ID. If the user enters an integer outside the array of shops, created with a Shop class, it will exit the loop and continue. Inside this loop is another while loop which calls the sellItem method of my Shop class below:
public Item sellItem()
{
displayItems();
int indexID = Shop.getInput();
if (indexID <= -1 || indexID >= wares.length)
{
System.out.println("Null"); // Testing purposes
return null;
}
else
{
return wares[indexID];
}
}
private void displayItems()
{
System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
System.out.println("0. Return to Shops");
for(int i = 0; i < wares.length; i++)
{
System.out.print(i + 1 + ". ");
System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
}
}
private static int getInput()
{
Scanner scanInput = new Scanner(System.in);
int itemID = scanInput.nextInt();
int indexID = itemID - 1;
return indexID;
}
The while loop in my main class method is as follows:
boolean exitAllShops = true;
while(exitAllShops)
{
System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
}
else
{
System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
int confirm = scan.nextInt();
if(confirm == 1)
{
exitAllShops = false;
}
}
The problem is here:
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
No matter what I do, I can't get "still null" to print to confirm that I'm correctly calling the return statement of the method sellItem of the class Shop. What am I doing wrong?
After calling allShops[...].sellItem(), allShops is still a valid array reference -- there's no way it could be null! You probably want to test the return value from sellItem:
if(allShops[shopInput-1].sellItem() == null)

Categories