Basically I am having trouble with my if statement. I would like it to say "No CDs found for " + val, however this is the output I am getting:
Welcome to the CD Database
Enter search, add, name, list, or quit:
name
Enter the full or partial name:
asdfa
Enter search, add, name, list, or quit:
as you can see it is not returning anything.
my code:
public void printByName(String val) {
int i = 0;
for (CompactDisc values : database.values()) {
if (values.getArtist().contains(val)) {
System.out.println(values);
} else if (i > database.size() && !values.getArtist().contains(val)) {
System.out.println("No CDs found for " + val);
}
i++;
}
}
for some reason my counter is not iterating and this has been driving me crazy for hours.I want it to say no CDs found after it loops through the hashmap and does not find a partial match of the string the user entered
additional output:
Welcome to the CD Database
Enter search, add, name, list, or quit:
name
Enter the full or partial name:
Mo
Artist:Modest Mouse Title:We Were Dead Before the Ship Even Sank price:5.99
Artist:Thelonious Monk Title:Monk's Dream price:5.99
Enter search, add, name, list, or quit:
list
Artist:Isley Brothers Title:Funky Family price:5.99
Artist:Muddy Waters Title:At Newport price:6.99
Artist:Sly & The Family Stone Title:Greatest Hits price:6.99
Artist:Modest Mouse Title:We Were Dead Before the Ship Even Sank price:5.99
Artist:St. Germain Title:Tourist price:5.99
Artist:Bob Dylan Title:Desire price:6.99
Artist:The Beatles Title:Abbey Road price:6.99
Artist:Los Straitjackets Title:The Velvet Touch of... price:5.99
Artist:The Velvet Underground Title:Peel Slowly and See price:6.99
Artist:Thelonious Monk Title:Monk's Dream price:5.99
Enter search, add, name, list, or quit:
quit
Program ending.
The condition i > database.size() will never be true because the loop will exit before i reaches the database size. Try changing your code to this:
public void printByName(String val) {
for (CompactDisc values : database.values()) {
if (values.getArtist().contains(val)) {
System.out.println(values);
} else {
System.out.println("No CDs found for " + val);
}
}
}
There is a problem in your logic structure.
Your 'if' is inside your "loop" block. It must be outside. Take a look:
public void printByName(String val) {
int i = 0;
for (CompactDisc values : database.values()) {
if (values.getArtist().contains(val)) {
System.out.println(values);
i++;
}
}
if (i==0) {
System.out.println("No CDs found for " + val);
}
}
It should be else if (i >= database.size() && !values.getArtist().contains(val))for the reason stated above.
Related
I'm struggling with dealing of inventory scan for my game, it basically search for the user inventory if "Flying Broom" if present(it was collected in another method and upload the code is too long), if not it will run the method challengedragon() again; else, it will proceed to the next challenge if the item is present.I was think of inserting method as parameter but it is not possible. This is what I have now. :
public class Main {
String Flyingbroom = "Flying broom";
public static void main(String[] args) {
Player_inventory p = new Player_inventory();
challengedragon();
}
public void challengedragon() {
System.out.println("a Hungarian Horntail dragon! Let's start the battle! You have four options to beat the dragon: ");
System.out.println("1: Fly away with your broom");
System.out.println("2: Fight the dragon");
System.out.println("3: Just run to the egg and get it");
System.out.println("4: Hide behind a rock");
System.out.println("5: Go back to Hogwart");
System.out.println("Your choice is: ");
Scanner in = new Scanner(System.in);
int dragonfightchoice = in .nextInt();
if (dragonfightchoice == 1) {
{
p.Scanitem(Flyingbroom,
"Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg",
"You dont have the broom. Try to search for the broom",
playerHP);
proceedtonextchallengelake();
} else if (dragonfightchoice == 2) {
System.out.println("The Hungarian Horntail dragon fired you. - 70HP. ");
playerHP -= 70;
challengedragon();
} else if (dragonfightchoice == 3) {
System.out.println("Bad idea... You lose 100 HP");
playerHP -= 100;
challengedragon();
} else if (dragonfightchoice == 4) {
System.out.println("The dragon found you. You lose 30 HP");
playerHP -= 30;
challengedragon();
} else if (dragonfightchoice == 5) {
Hogwart();
} else {
invalid();
challengedragon();
}
}
For my inventory class:
public void Scanitem(String item, String trueouputext, String textifconditionisnotmet) {
if (inv.contains(item) == true) {
System.out.println(trueouputext);
} else if (inv.contains(item) == false) {
System.out.println(textifconditionisnotmet);
}
public static ArrayList<String> inv = new ArrayList<String>();
Do you guys have any recommendation?
Are there additional steps to populate the inventory (variable inv)?
Also, wouldn't you want ScanItem to answer true or false, depending on whether the item was found? Then you would have something like this:
public boolean scanitem(String item) {
return ( inv.contains(item) );
}
if ( p.scanItem(flyingBroom) ) {
System.out.println("Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg");
} else {
System.out.println("You dont have the broom. Try to search for the broom");
}
That will get you closer to what you want. However, there are two other issues which you'll need to put into your code:
You will need a loop of some sort, instead of calling challengeDragon from inside of itself.
Somehow, the return value from scanItem must be used to decide whether to loop.
Currently, you do a nested call of a method each time the player does something, this means that sooner or later you'll run out of the stack. A better idea for the framework for your text-based adventure is to have some kind of a description of the current game's state. The state could be represented as an object that contains the following information:
where's the player currently at (on which step, at which "crossing" etc.)
the player's stats (HP, available skills etc.)
the contents of the player's inventory
some previously made choices affecting the game
Then, the code could be written as a simple loop that does the following:
process player's input
change the state according to the player's input
present the player with available options according to the new state
wait for the next input
repeat
I've created a for loop that lists all objects in my array-list but i need it to be a dynamic option menu that always ends with exit. I have used switch case option menu in other parts of the program in different methods. But I'm not sure how to create an incrementing case switch in here or if it would have to be put into the for loop?
private static void subCar(Scanner keyboard, CarLot carLot) {
if (carLot.getCar().size() == 0) {
System.out.println("No Cars on the Car Lot to Remove");
}else {
System.out.println("");
System.out.println("Cars Available to Remove: ");
System.out.printf("%-7s%-6s%-35s%-5s\n","Option"," ID","Make/Model/Year","Price");
for (int index=0; index < carLot.getCar().size(); index++) {
System.out.printf("%-7s%-6s%-2s%-5s\n",carLot.getCar().get(index).getID(),
carLot.getCar().get(index).getMake(),carLot.getCar().get(index).getModel(),
carLot.getCar().get(index).getPrice());
}
}
}
I'm trying to create a menu option so I can select which object to delete from my array-list
I want the output to look like this:
option ID Make/Model/Year Price
1. 2 Chevrolet cavalier 2000 1999.99
2. Exit
enter option:
exit option needs to always come last
Your last option will always be bigger then size of list of cars.
int option = //read it form scanner;
if (option > carLot.getCar().size()) {
// exit
} else {
carLot.getCar().remove(option);
}
To print all options and an exit one. You need to extract index outside the loop, loop and one print after loop. One of the example:
int index = 0;
for (; index < carLot.getCar().size(); index++) {
System.out.printf("%-7s%-6s%-2s%-5s\n",
index,
carLot.getCar().get(index).getID(),
carLot.getCar().get(index).getMake() + " " + carLot.getCar().get(index).getModel(),
carLot.getCar().get(index).getPrice());
}
System.out.printf("%-7s%-6s", index, "Exit");
I have a Java program that asks user questions and totals their scores. I am trying to display the correct total of answered questions at the end of the program. However, I have no idea how to, can some please help me!
Here is an example of how my code looks like l! But this is not my actual code this is from another source!
Import java.util.Scanner;
public class App
{
public static void main(String[] args) {
// The array of questions.
String questions[] = {
"Plants derive most of their dry mass from the air.",
"Aluminium is the most common metal in the Earth's crust.",
"Vitamin C has be shown to prevent colds.",
"We lose the most heat through our heads.",
"Dogs are unable to digest chocolate.",
"Apple pips contain cyanide.",
"Cholesterol is a nat
"When you're on a diet, you lose weight by oxidising fat to a gas and exhaling it.",
"Human beings are unable to sense when the oxygen level of the air is low.",
"Most of the Y chromosome is passed unchanged from father to son" };
// The array of answers. The entries correspond to the questions.
boolean answers[] = { true, true, false, false, false, true, false,
true, true, true };
// Display the opening text.
System.out.println("Answer each of the following questions with 't' (true) or 'f' (false)");
// We'll use this to get user input.
Scanner input = new Scanner(System.in);
// Add up the user's score here as we go along.
int score = 0;
// The is the index into the questions array and the answers array.
int questionNumber = 0;
// Create a blank line.
System.out.println();
// The do-while loop will keep running while questionNumber is less
// than the question array length.
do {
// Display the question
System.out.println(questions[questionNumber]);
// Display a little prompt to make it clearer that the user has to
// enter something.
System.out.print("> ");
// Get the user's answer.
String userAnswer = input.nextLine();
// Check that the user has entered t or f.
if (!userAnswer.equals("t") && !userAnswer.equals("f")) {
System.out.println("Please enter t for true or f for false.\n");
// Invalid input!
// Skip the rest of this loop iteration and ask the same question again.
continue;
}
// Check the answer.
if (userAnswer.equals("t") && answers[questionNumber] == true) {
// If the answer's t and the right answer is "true", the answer was correct.
score++;
System.out.println("correct\n");
} else if (userAnswer.equals("f") && answers[questionNumber] == false) {
// If the answer's f and the correct answer is "false", the answer was correct.
System.out.println("correct\n");
score++;
}
else {
// Wrong answer!
System.out.println("incorrect!\n");
}
// Now we can move to the next question when we go round the loop again.
questionNumber++;
} while (questionNumber < questions.length); // end of do-while.
// This isn't really necessary, but closing the Scanner prevents a warning icon in Eclipse.
input.close();
// Tell the user their score.
System.out.println("You scored: " + score);
// Rank the score! Only one of the alternatives below will execute.
// Java will check them in order from top to bottom.
if(score < 5) {
// Less than 5 -- not so good.
System.out.println("Hmmm, maybe you're the artistic type. Try the test again!");
}
else if(score < 8) {
// The score wasn't less than 5, but it IS less than 8.
System.out.println("Not bad! But have another go.");
}
else if(score <= 9) {
// The score wasn't less than 8, but it IS less than, or equal to, 9.
System.out.println("Pretty good! But no perfect. Try again!");
}
else {
// The score was more than 9 -- must be 10 because we've only got 10 questions.
System.out.println("You're a certified science genius!");
}
}
}
You can use a list and add the question nummer when the user has answered the question correctly.
Before your do-while-loop you have to add
ArrayList<Integer> correctQuestions = new ArrayList<Integer>();
Then in your do-while-loop you have to add when the answer is correct
correctQuestions.add(questionNumber);
At the end of you program (outside the do-while-loop) you can make the output like this:
System.out.println("You answered the following questions correctly");
for (int k : correctQuestions) {
System.out.println(questions[k]);
}
Simply declare a boolean array containing user answers in your class:
public boolean[] userAnswers = new boolean[questions.length]; //remove the access modifier if you want to declare the array inside main instead of the class
Now in your do-while loop, after parsing the user input, do this:
userAnswers[questionNumber] = userAnswer.equals("t");
Outside of your do-while loop (after you close the Scanner), do the following to print all the questions and the user's answer:
for (int i = 0; i < questions.length; i++) {
System.out.println("User answered \"" + userAnswers[i] + "\" on question " + (i + 1) + ": " + questions[i]);
}
I'm trying to create a console app that iterates through an arrayList of meal ideas every time the correct menu item is selected. The problem is that I can't seem to continue the iteration every time the correct menu item is selected, it just restarts the loop.
Scanner in = new Scanner(System.in);
ArrayList<String> meals = new ArrayList<String>();
meals.add("pasta");
meals.add("potatoes");
meals.add("pork");
String select = "";
while(!select.equals("q")){
System.out.println("What would you like to do?");
System.out.println("\t 1. See next suggestion.");
System.out.println("\t 2. <Another option>");
System.out.println("\t 3. <Another option>");
select = in.next();
switch(select){
case "1":
//Here's where the problem is:
int nextIdea = 0;
while(){
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
break;
}
System.in.read();
break;
}
}
After the user selects to show the daily selection, the first item in the list should be displayed then it should go back to the "What would you like to do menu" then next time the user selects option 1 in the menu it should display the next item in the menu but instead it restarts the loop. I understand it's because the counter variable ("nextIdea") is set to zero every time before the loop executes but how can I get it to remember which arrayList index number was last used and then use that next time the user selects to see the daily meal. The list should only reset to 0 once it's gone through all the items in the list.
Any help would be appreciated, thank you!!
You need to move the nextIdea index out of the first loop. Then you also don't have to iterate the list when the user selects "See next suggestion." - You just display the next idea:
int nextIdea = 0;
while(!select.equals("q")){
System.out.println("What would you like to do?");
System.out.println("\t 1. See next suggestion.");
System.out.println("\t 2. <Another option>");
System.out.println("\t 3. <Another option>");
select = in.next();
switch(select){
case "1":
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
System.in.read();
break;
}
}
So, basically, you don't need the inner loop to iterate over the meal ideas. You already do the iteration with the outside loop: Every time the user selects menu item #1, you show her the next idea.
You should also make sure that nextIdea is always a valid index in the array list. Something like:
case "1":
if(nextIdea >= meals.size()) {
nextIdea = 0;
}
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
System.in.read();
break;
Firstly, instantiate nextIdea outside of the while loop like you have mentioned.
Then, includ a simple if statement which checks if the nextIdea has reached the end, like so:
while(true)
{
if (nextIdea < meals.size())
{
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
}
else
{
nextIdea = 0;
}
break;
}
You didn't have a condition in the while loop, so I'm assuming you meant 'true' which means it'll run infinitely until broken out of.
Although, technically, the loop here isn't really doing anything as it just runs once and breaks out, so you can just get rid of it like so:
if (nextIdea < meals.size())
{
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
}
else
{
nextIdea = 0;
}
I think you need to think carefully about what it is you actually want to achieve and what the best way to do this is.
Feel free to ask my further questions.
I'm trying to make a simple text based adventure as an exercise on beginner java, but I've ran into a problem, and after a long time of searching I decided to just ask it.
I want to know how to refire this loop after IF statement has been answered, eg. user inputs: "Help", help tab shows up and user can enter another command.
I'm clueless as to why this doesn't work, so any help would be much appreciated.
boolean loopone = false;
do {
System.out.println(name + " is standing in a forest, covered in slime goo.");
String cmdone = in.next();
if (cmdone.equals("Help")) {
System.out.println("---------Help---------");
System.out.println("Type: [Help] to view help");
System.out.println("Type: [Turn] to turn, syntax: [Turn (direction)] left, right and backward are the possible directions");
System.out.println("Type: [Enter] to go through an entrance");
System.out.println("Type: [Slay] to kill stuff");
System.out.println("Type: [Take] to take stuff");
System.out.println("Typing: [/rocket smallbrains] has no effect here");
return;
}
else if (cmdone.equals("Enter")){
System.out.println("Enter what?");
String conone = in.next();
if (conone.equals("Forest") || conone.equals("The forest")){
System.out.println("You're already in the forest, dummy!");
}
else{
System.out.println("I don't know where that is");
}
}
else if (cmdone.equals("Turn right")){
System.out.println("You turn right");
}
continue;
}while (loopone = false);
One issue is you need to make this:
}while (loopone = false);
this:
}while (loopone == false);
Otherwise, you just need to make sure that you are setting loopone to false in each of the if statements. When you want to exit, you set loopone to true (loopone = true).