问:
k.next statement
Here is my choose your own adventure project. There are no issues, apart after choosing this set of options (you don't have to read the whole thing):

```<code>1.name
2.no
3.hide, it asks you to input another answer.
</code>```

It does not matter what you put in, the second time, as it will still run the program according to "hide". Just wondering why this is showing up. Also, feel free to enjoy my game.

```<code>import java.util.Scanner;
public class BEproject1V2 {
    public static void main(String[] args) {
        Scanner k = new Scanner(System. in );
        String C1, C2, C2a, C3, C3a, C3b, C3c;
        System.out.println("Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.");
        System.out.println("First order of business, is choosing your Pirate Name! What is yarr real name?");
        String name = k.nextLine();
        String Pn = "Capn Cornelious Coxswain, The Hatless";

        ///Start of story
        System.out.println("Scupper that sailor! We'll call you " + Pn);
        System.out.println("Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.");
        System.out.println("Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!");
        System.out.println("'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.");
        System.out.println("You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!");
        System.out.println("The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.");
        System.out.println("She be lookin like the end for ol' " + Pn + ", until a giant sea turtle swims up to ye.");
        System.out.println("'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'");

        System.out.println("Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)");

        ////First choice "Yes"
        C1 = k.next();

        if (C1.equalsIgnoreCase("yes")) {
            System.out.println("King Randy takes you to the surface. 'I know of two Islands, the first being the Island of the screaming crabs,");
            System.out.println("or the Island of the Pun Telling Trees. which would you like to go to?' (Crab or Tree)");

            ////Second choice "Crab"
            C2 = k.next();
            if (C2.equalsIgnoreCase("Crab")) {
                System.out.println("'Okay! Here we go!'. King Randy takes off towards a distant land. You come about to a crab staring you dead in the face.");
                System.out.println("'Blast', you think to yourself. Ye see the crab take a lung of breath, waiting for the worst screamin crab ever recorded.");
                System.out.println("'CAPN CORNELIOUS COXSWAIN, THE HATLESS!'. The crab repeats, as it starts pinching your nose. Angered and afraid, you pick up a nearby rock.");
                System.out.println("Do you 'throw' the rock, or 'wait' for the crab to scream again?");

                ////Third choice "Throw"
                C3 = k.next();
                if (C3.equalsIgnoreCase("Throw")) {
                    System.out.println("You throw the rock somewhere in the distance. Why wouldn't you you aim it at the crab?");
                    System.out.println("Now you're defenseless, and an idiot in the eyes of crabs. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
                ////Third Choice else "Wait"
                else if (C3.equalsIgnoreCase("Wait")) {
                    System.out.println("You wait, and the crab starts screaming again. You notice that the tones ");
                    System.out.println("are in a pattern, so you sing along. The beautiful harmonies intrigue ");
                    System.out.println("the rest of the crabs, who then celebrate your presence. You win the island!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
            }
            ////Second Choice else "Tree"
            else if (C2.equalsIgnoreCase("Tree")) {
                System.out.println("'Fantastic choice!' says Randy. He takes you to the island, where you hear lots of moans and small chuckles. You reach the sand, and walk up to a line of trees.");
                System.out.println("'Is that a pirate over there?' asks one of the trees. 'Yes I think so! Hey I heard they were really good singers!' incorrectly states another.");
                System.out.println("'Why is that?' you ask. 'Because they can always hit the HIGH C'S!!' says the tree, bursting with laughter. 'I guess that's a little funny' you mumble to yourself.");
                System.out.println("'Oh you're in for a real TREEt then Cap'n! I have one for you.'Why should you pull your plate closer while eating spaghetti?' asks the tree. Do you answer? (Yes or no)");

                ////Third Choice 2 "Yes"
                C3a = k.next();
                if (C3a.equalsIgnoreCase("yes")) {
                    System.out.println("'So you don't spill any of it?' you say, immediately regretting your answer. You know that the tree is staring at you, even if it doesn't have eyes.");
                    System.out.println("'That was MY PUN.' exclaims the tree. 'NOW YOU WILL NEVER KNOW THE ANSWER, and are BANISHED from my PUNS, STINKy pirate.' Knowing you will never hear the pun, fills you with sadness. ");
                    System.out.println("Your eyes begin to sting, and you start shedding tears of soy. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 2 else "No"
                else if (C3a.equalsIgnoreCase("no")) {
                    System.out.println("'Hm I'm not sure!' you say. The tree chuckles harmoniously. 'So you'll get less-on-ya! HAHAHAHA!'. After contemplating your death from this joke, you decide to laugh with the tree.");
                    System.out.println("Knowing that you will be great friends, fills you with determination. YOU WIN!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please hit \"run\" to try again.");
                }
            }
        }
        ////First Choice else "No"
        else if (C1.equalsIgnoreCase("no")) {
            System.out.println("'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is ");
            System.out.println("a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?");

            ////Second Choice 2 "Raft"
            C2a = k.next();
            if (C2a.equalsIgnoreCase("swim")) {
                System.out.println("You begin to swim, and the shark chases right after you! You are able to avoid it, and make it to the raft. You look down and see that the shark is not chasing you, ");
                System.out.println("but being chased himself! A blue whale swallows the shark whole as he screams for his wife. You see a paddle out in the water, do you try to 'grab' it before Moby Dick himself ");
                System.out.println("consumes you? Or do you 'stay' on the raft?");
            }
            ////Third Choice 3 "Grab"
            C3b = k.next();
            if (C3b.equalsIgnoreCase("grab")) {
                System.out.println("You lunge for the paddle! Now is your time, and you start swimming faster and harder than ever before. You reach for it and - you got it! As you start to swim towards ");
                System.out.println("the raft. You make it, and start paddling to a nearby island. From where you are, you think you can hear a mixture of screaming and laughing... YOU WIN!");
                System.out.println("Thank you for playing my adventure, press run to play again.");
            }
            ////Third Choice 3 "Stay"
            else if (C3b.equalsIgnoreCase("stay")) {
                System.out.println("You decide to stay on the raft. Good choice, that paddle looked real dangerous. The whale can not get close enough due to the wreckage to attack you.");
                System.out.println("In a fit of fury, the whale breaches the water and says 'Caw! Caw!'. The whale then starts to fly! He is getting a LOT of air, but he is coming your way.  ");
                System.out.println("You realize that there is nothing you can do but watch the beauty of the whale come crashing down onto you. 'Take me as I am' are the last words to leave " + Pn + "'s mouth. THE END.");
                System.out.println("Thank you for playing my adventure, press run to play again.");
            }
            ////Third Choice 4 "Swim"
            else if (C2a.equalsIgnoreCase("hide")) {
                System.out.println("You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie ");
                System.out.println("'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie, ");
                System.out.println("'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize ");
                System.out.println("that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?");

                //// Third Choice 5 "60"
                C3c = k.next();
                if (C3c.equalsIgnoreCase("DVD")) {
                    System.out.println("You start screaming the tune of 'We Are The Champions' to distract the mermaid. It serenades her into a deep slumber. You STEAL a DVD, Indiana Jones style. However, ");
                    System.out.println("you have not brought anything to replace the DVD with. The entire cave begins to rumble, and you are suddenly about to be crushed by a rolling boulder, also ");
                    System.out.println("Indiana Jones style! The only difference is you get crushed by the boulder, THE END.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 6 "guess"
                else if (C3c.equalsIgnoreCase("guess")) {
                    System.out.println("Please insert your guess into me! (Number)");
                    int num = k.nextInt();
                    double bignum = Math.PI * Math.pow(num, 2);
                    System.out.println("'Hmmm my guess is " + num + "!'. 'So close!' says the mermaid. But the answer is actually " + bignum + "! I'm sorry but you aren't qualified to touch my DVD's.'");
                    System.out.println(" You gaze at the wet pile of DVD's and cry tears of soy. When it hits the water, you realize what your life has become. Seeing that murky reflection fills ");
                    System.out.println("you with sadness. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please run again.");
                }

            }
        }
    }
}
</code>```

答:
I believe this is how you wanted it to run:

```<code>Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.
First order of business, is choosing your Pirate Name! What is yarr real name?
    :me me big boy
Scupper that sailor! We'll call you Capn Cornelious Coxswain, The Hatless
Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.
Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!
'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.
You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!
The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.
She be lookin like the end for ol' Capn Cornelious Coxswain, The Hatless, until a giant sea turtle swims up to ye.
'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'
Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)
    :no
'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is
a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?
    :hide
You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie
'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie,
'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize
that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?
</code>```

If yes, your problem was that you had your Third choice outside your check for the Second choice C2a.equalsIgnoreCase("swim"), and you put your else after C3b.equalsIgnoreCase("stay"). This caused your program to check if the second choice is swim, if yes print your text, else just take the third choice without printing. By placing the third choice into the second choice swim block, and fixing the else (C2a.equalsIgnoreCase("hide")) it runs correctly.

```<code>Scanner k = new Scanner(System.in);
        String C1, C2, C2a, C3, C3a, C3b, C3c;
        System.out.println("Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.");
        System.out.println("First order of business, is choosing your Pirate Name! What is yarr real name?");
        String name = k.nextLine();
        String Pn = "Capn Cornelious Coxswain, The Hatless";

        ///Start of story
        System.out.println("Scupper that sailor! We'll call you " + Pn);
        System.out.println("Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.");
        System.out.println("Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!");
        System.out.println("'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.");
        System.out.println("You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!");
        System.out.println("The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.");
        System.out.println("She be lookin like the end for ol' " + Pn + ", until a giant sea turtle swims up to ye.");
        System.out.println("'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'");

        System.out.println("Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)");

        ////First choice "Yes"
        C1 = k.next();
        if (C1.equalsIgnoreCase("yes")) {
            System.out.println("King Randy takes you to the surface. 'I know of two Islands, the first being the Island of the screaming crabs,");
            System.out.println("or the Island of the Pun Telling Trees. which would you like to go to?' (Crab or Tree)");

            ////Second choice "Crab"
            C2 = k.next();
            if (C2.equalsIgnoreCase("Crab")) {

                System.out.println("'Okay! Here we go!'. King Randy takes off towards a distant land. You come about to a crab staring you dead in the face.");
                System.out.println("'Blast', you think to yourself. Ye see the crab take a lung of breath, waiting for the worst screamin crab ever recorded.");
                System.out.println("'CAPN CORNELIOUS COXSWAIN, THE HATLESS!'. The crab repeats, as it starts pinching your nose. Angered and afraid, you pick up a nearby rock.");
                System.out.println("Do you 'throw' the rock, or 'wait' for the crab to scream again?");

                ////Third choice "Throw"
                C3 = k.next();
                if (C3.equalsIgnoreCase("Throw")) {
                    System.out.println("You throw the rock somewhere in the distance. Why wouldn't you you aim it at the crab?");
                    System.out.println("Now you're defenseless, and an idiot in the eyes of crabs. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
                ////Third Choice else "Wait"
                else if (C3.equalsIgnoreCase("Wait")) {
                    System.out.println("You wait, and the crab starts screaming again. You notice that the tones ");
                    System.out.println("are in a pattern, so you sing along. The beautiful harmonies intrigue ");
                    System.out.println("the rest of the crabs, who then celebrate your presence. You win the island!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
            }
            ////Second Choice else "Tree"
            else if (C2.equalsIgnoreCase("Tree")) {
                System.out.println("'Fantastic choice!' says Randy. He takes you to the island, where you hear lots of moans and small chuckles. You reach the sand, and walk up to a line of trees.");
                System.out.println("'Is that a pirate over there?' asks one of the trees. 'Yes I think so! Hey I heard they were really good singers!' incorrectly states another.");
                System.out.println("'Why is that?' you ask. 'Because they can always hit the HIGH C'S!!' says the tree, bursting with laughter. 'I guess that's a little funny' you mumble to yourself.");
                System.out.println("'Oh you're in for a real TREEt then Cap'n! I have one for you.'Why should you pull your plate closer while eating spaghetti?' asks the tree. Do you answer? (Yes or no)");

                ////Third Choice 2 "Yes"
                C3a = k.next();
                if (C3a.equalsIgnoreCase("yes")) {
                    System.out.println("'So you don't spill any of it?' you say, immediately regretting your answer. You know that the tree is staring at you, even if it doesn't have eyes.");
                    System.out.println("'That was MY PUN.' exclaims the tree. 'NOW YOU WILL NEVER KNOW THE ANSWER, and are BANISHED from my PUNS, STINKy pirate.' Knowing you will never hear the pun, fills you with sadness. ");
                    System.out.println("Your eyes begin to sting, and you start shedding tears of soy. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 2 else "No"
                else if (C3a.equalsIgnoreCase("no")) {
                    System.out.println("'Hm I'm not sure!' you say. The tree chuckles harmoniously. 'So you'll get less-on-ya! HAHAHAHA!'. After contemplating your death from this joke, you decide to laugh with the tree.");
                    System.out.println("Knowing that you will be great friends, fills you with determination. YOU WIN!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please hit \"run\" to try again.");
                }
            }
        }
        ////First Choice else "No"
        else if (C1.equalsIgnoreCase("no")) {
            System.out.println("'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is ");
            System.out.println("a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?");

            ////Second Choice 2 "Raft"
            C2a = k.next();
            if (C2a.equalsIgnoreCase("swim")) {
                System.out.println("You begin to swim, and the shark chases right after you! You are able to avoid it, and make it to the raft. You look down and see that the shark is not chasing you, ");
                System.out.println("but being chased himself! A blue whale swallows the shark whole as he screams for his wife. You see a paddle out in the water, do you try to 'grab' it before Moby Dick himself ");
                System.out.println("consumes you? Or do you 'stay' on the raft?");

////Third Choice 3 "Grab"
                C3b = k.next();
                if (C3b.equalsIgnoreCase("grab")) {
                    System.out.println("You lunge for the paddle! Now is your time, and you start swimming faster and harder than ever before. You reach for it and - you got it! As you start to swim towards ");
                    System.out.println("the raft. You make it, and start paddling to a nearby island. From where you are, you think you can hear a mixture of screaming and laughing... YOU WIN!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 3 "Stay"
                else if (C3b.equalsIgnoreCase("stay")) {
                    System.out.println("You decide to stay on the raft. Good choice, that paddle looked real dangerous. The whale can not get close enough due to the wreckage to attack you.");
                    System.out.println("In a fit of fury, the whale breaches the water and says 'Caw! Caw!'. The whale then starts to fly! He is getting a LOT of air, but he is coming your way.  ");
                    System.out.println("You realize that there is nothing you can do but watch the beauty of the whale come crashing down onto you. 'Take me as I am' are the last words to leave " + Pn + "'s mouth. THE END.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
            }

            ////Third Choice 4 "Swim"
            if (C2a.equalsIgnoreCase("hide")) {
                System.out.println("You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie ");
                System.out.println("'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie, ");
                System.out.println("'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize ");
                System.out.println("that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?");

                //// Third Choice 5 "60"
                C3c = k.next();
                if (C3c.equalsIgnoreCase("DVD")) {
                    System.out.println("You start screaming the tune of 'We Are The Champions' to distract the mermaid. It serenades her into a deep slumber. You STEAL a DVD, Indiana Jones style. However, ");
                    System.out.println("you have not brought anything to replace the DVD with. The entire cave begins to rumble, and you are suddenly about to be crushed by a rolling boulder, also ");
                    System.out.println("Indiana Jones style! The only difference is you get crushed by the boulder, THE END.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 6 "guess"
                else if (C3c.equalsIgnoreCase("guess")) {
                    System.out.println("Please insert your guess into me! (Number)");
                    int num = k.nextInt();
                    double bignum = Math.PI * Math.pow(num, 2);
                    System.out.println("'Hmmm my guess is " + num + "!'. 'So close!' says the mermaid. But the answer is actually " + bignum + "! I'm sorry but you aren't qualified to touch my DVD's.'");
                    System.out.println(" You gaze at the wet pile of DVD's and cry tears of soy. When it hits the water, you realize what your life has become. Seeing that murky reflection fills ");
                    System.out.println("you with sadness. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please run again.");
                }

            }
        }
</code>```

I hope this is what you wanted.

Title: k.next statement

Body:
Here is my choose your own adventure project. There are no issues, apart after choosing this set of options (you don't have to read the whole thing):

1.name
2.no
3.hide, it asks you to input another answer.

It does not matter what you put in, the second time, as it will still run the program according to "hide". Just wondering why this is showing up. Also, feel free to enjoy my game.

import java.util.Scanner;
public class BEproject1V2 {
    public static void main(String[] args) {
        Scanner k = new Scanner(System. in );
        String C1, C2, C2a, C3, C3a, C3b, C3c;
        System.out.println("Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.");
        System.out.println("First order of business, is choosing your Pirate Name! What is yarr real name?");
        String name = k.nextLine();
        String Pn = "Capn Cornelious Coxswain, The Hatless";

        ///Start of story
        System.out.println("Scupper that sailor! We'll call you " + Pn);
        System.out.println("Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.");
        System.out.println("Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!");
        System.out.println("'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.");
        System.out.println("You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!");
        System.out.println("The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.");
        System.out.println("She be lookin like the end for ol' " + Pn + ", until a giant sea turtle swims up to ye.");
        System.out.println("'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'");

        System.out.println("Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)");

        ////First choice "Yes"
        C1 = k.next();

        if (C1.equalsIgnoreCase("yes")) {
            System.out.println("King Randy takes you to the surface. 'I know of two Islands, the first being the Island of the screaming crabs,");
            System.out.println("or the Island of the Pun Telling Trees. which would you like to go to?' (Crab or Tree)");

            ////Second choice "Crab"
            C2 = k.next();
            if (C2.equalsIgnoreCase("Crab")) {
                System.out.println("'Okay! Here we go!'. King Randy takes off towards a distant land. You come about to a crab staring you dead in the face.");
                System.out.println("'Blast', you think to yourself. Ye see the crab take a lung of breath, waiting for the worst screamin crab ever recorded.");
                System.out.println("'CAPN CORNELIOUS COXSWAIN, THE HATLESS!'. The crab repeats, as it starts pinching your nose. Angered and afraid, you pick up a nearby rock.");
                System.out.println("Do you 'throw' the rock, or 'wait' for the crab to scream again?");

                ////Third choice "Throw"
                C3 = k.next();
                if (C3.equalsIgnoreCase("Throw")) {
                    System.out.println("You throw the rock somewhere in the distance. Why wouldn't you you aim it at the crab?");
                    System.out.println("Now you're defenseless, and an idiot in the eyes of crabs. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
                ////Third Choice else "Wait"
                else if (C3.equalsIgnoreCase("Wait")) {
                    System.out.println("You wait, and the crab starts screaming again. You notice that the tones ");
                    System.out.println("are in a pattern, so you sing along. The beautiful harmonies intrigue ");
                    System.out.println("the rest of the crabs, who then celebrate your presence. You win the island!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
            }
            ////Second Choice else "Tree"
            else if (C2.equalsIgnoreCase("Tree")) {
                System.out.println("'Fantastic choice!' says Randy. He takes you to the island, where you hear lots of moans and small chuckles. You reach the sand, and walk up to a line of trees.");
                System.out.println("'Is that a pirate over there?' asks one of the trees. 'Yes I think so! Hey I heard they were really good singers!' incorrectly states another.");
                System.out.println("'Why is that?' you ask. 'Because they can always hit the HIGH C'S!!' says the tree, bursting with laughter. 'I guess that's a little funny' you mumble to yourself.");
                System.out.println("'Oh you're in for a real TREEt then Cap'n! I have one for you.'Why should you pull your plate closer while eating spaghetti?' asks the tree. Do you answer? (Yes or no)");

                ////Third Choice 2 "Yes"
                C3a = k.next();
                if (C3a.equalsIgnoreCase("yes")) {
                    System.out.println("'So you don't spill any of it?' you say, immediately regretting your answer. You know that the tree is staring at you, even if it doesn't have eyes.");
                    System.out.println("'That was MY PUN.' exclaims the tree. 'NOW YOU WILL NEVER KNOW THE ANSWER, and are BANISHED from my PUNS, STINKy pirate.' Knowing you will never hear the pun, fills you with sadness. ");
                    System.out.println("Your eyes begin to sting, and you start shedding tears of soy. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 2 else "No"
                else if (C3a.equalsIgnoreCase("no")) {
                    System.out.println("'Hm I'm not sure!' you say. The tree chuckles harmoniously. 'So you'll get less-on-ya! HAHAHAHA!'. After contemplating your death from this joke, you decide to laugh with the tree.");
                    System.out.println("Knowing that you will be great friends, fills you with determination. YOU WIN!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please hit \"run\" to try again.");
                }
            }
        }
        ////First Choice else "No"
        else if (C1.equalsIgnoreCase("no")) {
            System.out.println("'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is ");
            System.out.println("a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?");

            ////Second Choice 2 "Raft"
            C2a = k.next();
            if (C2a.equalsIgnoreCase("swim")) {
                System.out.println("You begin to swim, and the shark chases right after you! You are able to avoid it, and make it to the raft. You look down and see that the shark is not chasing you, ");
                System.out.println("but being chased himself! A blue whale swallows the shark whole as he screams for his wife. You see a paddle out in the water, do you try to 'grab' it before Moby Dick himself ");
                System.out.println("consumes you? Or do you 'stay' on the raft?");
            }
            ////Third Choice 3 "Grab"
            C3b = k.next();
            if (C3b.equalsIgnoreCase("grab")) {
                System.out.println("You lunge for the paddle! Now is your time, and you start swimming faster and harder than ever before. You reach for it and - you got it! As you start to swim towards ");
                System.out.println("the raft. You make it, and start paddling to a nearby island. From where you are, you think you can hear a mixture of screaming and laughing... YOU WIN!");
                System.out.println("Thank you for playing my adventure, press run to play again.");
            }
            ////Third Choice 3 "Stay"
            else if (C3b.equalsIgnoreCase("stay")) {
                System.out.println("You decide to stay on the raft. Good choice, that paddle looked real dangerous. The whale can not get close enough due to the wreckage to attack you.");
                System.out.println("In a fit of fury, the whale breaches the water and says 'Caw! Caw!'. The whale then starts to fly! He is getting a LOT of air, but he is coming your way.  ");
                System.out.println("You realize that there is nothing you can do but watch the beauty of the whale come crashing down onto you. 'Take me as I am' are the last words to leave " + Pn + "'s mouth. THE END.");
                System.out.println("Thank you for playing my adventure, press run to play again.");
            }
            ////Third Choice 4 "Swim"
            else if (C2a.equalsIgnoreCase("hide")) {
                System.out.println("You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie ");
                System.out.println("'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie, ");
                System.out.println("'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize ");
                System.out.println("that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?");

                //// Third Choice 5 "60"
                C3c = k.next();
                if (C3c.equalsIgnoreCase("DVD")) {
                    System.out.println("You start screaming the tune of 'We Are The Champions' to distract the mermaid. It serenades her into a deep slumber. You STEAL a DVD, Indiana Jones style. However, ");
                    System.out.println("you have not brought anything to replace the DVD with. The entire cave begins to rumble, and you are suddenly about to be crushed by a rolling boulder, also ");
                    System.out.println("Indiana Jones style! The only difference is you get crushed by the boulder, THE END.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 6 "guess"
                else if (C3c.equalsIgnoreCase("guess")) {
                    System.out.println("Please insert your guess into me! (Number)");
                    int num = k.nextInt();
                    double bignum = Math.PI * Math.pow(num, 2);
                    System.out.println("'Hmmm my guess is " + num + "!'. 'So close!' says the mermaid. But the answer is actually " + bignum + "! I'm sorry but you aren't qualified to touch my DVD's.'");
                    System.out.println(" You gaze at the wet pile of DVD's and cry tears of soy. When it hits the water, you realize what your life has become. Seeing that murky reflection fills ");
                    System.out.println("you with sadness. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please run again.");
                }

            }
        }
    }
}

Body:
I believe this is how you wanted it to run:

Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.
First order of business, is choosing your Pirate Name! What is yarr real name?
    :me me big boy
Scupper that sailor! We'll call you Capn Cornelious Coxswain, The Hatless
Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.
Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!
'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.
You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!
The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.
She be lookin like the end for ol' Capn Cornelious Coxswain, The Hatless, until a giant sea turtle swims up to ye.
'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'
Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)
    :no
'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is
a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?
    :hide
You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie
'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie,
'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize
that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?

If yes, your problem was that you had your Third choice outside your check for the Second choice C2a.equalsIgnoreCase("swim"), and you put your else after C3b.equalsIgnoreCase("stay"). This caused your program to check if the second choice is swim, if yes print your text, else just take the third choice without printing. By placing the third choice into the second choice swim block, and fixing the else (C2a.equalsIgnoreCase("hide")) it runs correctly.

Scanner k = new Scanner(System.in);
        String C1, C2, C2a, C3, C3a, C3b, C3c;
        System.out.println("Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.");
        System.out.println("First order of business, is choosing your Pirate Name! What is yarr real name?");
        String name = k.nextLine();
        String Pn = "Capn Cornelious Coxswain, The Hatless";

        ///Start of story
        System.out.println("Scupper that sailor! We'll call you " + Pn);
        System.out.println("Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.");
        System.out.println("Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!");
        System.out.println("'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.");
        System.out.println("You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!");
        System.out.println("The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.");
        System.out.println("She be lookin like the end for ol' " + Pn + ", until a giant sea turtle swims up to ye.");
        System.out.println("'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'");

        System.out.println("Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)");

        ////First choice "Yes"
        C1 = k.next();
        if (C1.equalsIgnoreCase("yes")) {
            System.out.println("King Randy takes you to the surface. 'I know of two Islands, the first being the Island of the screaming crabs,");
            System.out.println("or the Island of the Pun Telling Trees. which would you like to go to?' (Crab or Tree)");

            ////Second choice "Crab"
            C2 = k.next();
            if (C2.equalsIgnoreCase("Crab")) {

                System.out.println("'Okay! Here we go!'. King Randy takes off towards a distant land. You come about to a crab staring you dead in the face.");
                System.out.println("'Blast', you think to yourself. Ye see the crab take a lung of breath, waiting for the worst screamin crab ever recorded.");
                System.out.println("'CAPN CORNELIOUS COXSWAIN, THE HATLESS!'. The crab repeats, as it starts pinching your nose. Angered and afraid, you pick up a nearby rock.");
                System.out.println("Do you 'throw' the rock, or 'wait' for the crab to scream again?");

                ////Third choice "Throw"
                C3 = k.next();
                if (C3.equalsIgnoreCase("Throw")) {
                    System.out.println("You throw the rock somewhere in the distance. Why wouldn't you you aim it at the crab?");
                    System.out.println("Now you're defenseless, and an idiot in the eyes of crabs. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
                ////Third Choice else "Wait"
                else if (C3.equalsIgnoreCase("Wait")) {
                    System.out.println("You wait, and the crab starts screaming again. You notice that the tones ");
                    System.out.println("are in a pattern, so you sing along. The beautiful harmonies intrigue ");
                    System.out.println("the rest of the crabs, who then celebrate your presence. You win the island!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");

                }
            }
            ////Second Choice else "Tree"
            else if (C2.equalsIgnoreCase("Tree")) {
                System.out.println("'Fantastic choice!' says Randy. He takes you to the island, where you hear lots of moans and small chuckles. You reach the sand, and walk up to a line of trees.");
                System.out.println("'Is that a pirate over there?' asks one of the trees. 'Yes I think so! Hey I heard they were really good singers!' incorrectly states another.");
                System.out.println("'Why is that?' you ask. 'Because they can always hit the HIGH C'S!!' says the tree, bursting with laughter. 'I guess that's a little funny' you mumble to yourself.");
                System.out.println("'Oh you're in for a real TREEt then Cap'n! I have one for you.'Why should you pull your plate closer while eating spaghetti?' asks the tree. Do you answer? (Yes or no)");

                ////Third Choice 2 "Yes"
                C3a = k.next();
                if (C3a.equalsIgnoreCase("yes")) {
                    System.out.println("'So you don't spill any of it?' you say, immediately regretting your answer. You know that the tree is staring at you, even if it doesn't have eyes.");
                    System.out.println("'That was MY PUN.' exclaims the tree. 'NOW YOU WILL NEVER KNOW THE ANSWER, and are BANISHED from my PUNS, STINKy pirate.' Knowing you will never hear the pun, fills you with sadness. ");
                    System.out.println("Your eyes begin to sting, and you start shedding tears of soy. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 2 else "No"
                else if (C3a.equalsIgnoreCase("no")) {
                    System.out.println("'Hm I'm not sure!' you say. The tree chuckles harmoniously. 'So you'll get less-on-ya! HAHAHAHA!'. After contemplating your death from this joke, you decide to laugh with the tree.");
                    System.out.println("Knowing that you will be great friends, fills you with determination. YOU WIN!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please hit \"run\" to try again.");
                }
            }
        }
        ////First Choice else "No"
        else if (C1.equalsIgnoreCase("no")) {
            System.out.println("'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is ");
            System.out.println("a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?");

            ////Second Choice 2 "Raft"
            C2a = k.next();
            if (C2a.equalsIgnoreCase("swim")) {
                System.out.println("You begin to swim, and the shark chases right after you! You are able to avoid it, and make it to the raft. You look down and see that the shark is not chasing you, ");
                System.out.println("but being chased himself! A blue whale swallows the shark whole as he screams for his wife. You see a paddle out in the water, do you try to 'grab' it before Moby Dick himself ");
                System.out.println("consumes you? Or do you 'stay' on the raft?");

////Third Choice 3 "Grab"
                C3b = k.next();
                if (C3b.equalsIgnoreCase("grab")) {
                    System.out.println("You lunge for the paddle! Now is your time, and you start swimming faster and harder than ever before. You reach for it and - you got it! As you start to swim towards ");
                    System.out.println("the raft. You make it, and start paddling to a nearby island. From where you are, you think you can hear a mixture of screaming and laughing... YOU WIN!");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 3 "Stay"
                else if (C3b.equalsIgnoreCase("stay")) {
                    System.out.println("You decide to stay on the raft. Good choice, that paddle looked real dangerous. The whale can not get close enough due to the wreckage to attack you.");
                    System.out.println("In a fit of fury, the whale breaches the water and says 'Caw! Caw!'. The whale then starts to fly! He is getting a LOT of air, but he is coming your way.  ");
                    System.out.println("You realize that there is nothing you can do but watch the beauty of the whale come crashing down onto you. 'Take me as I am' are the last words to leave " + Pn + "'s mouth. THE END.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
            }

            ////Third Choice 4 "Swim"
            if (C2a.equalsIgnoreCase("hide")) {
                System.out.println("You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie ");
                System.out.println("'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie, ");
                System.out.println("'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize ");
                System.out.println("that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?");

                //// Third Choice 5 "60"
                C3c = k.next();
                if (C3c.equalsIgnoreCase("DVD")) {
                    System.out.println("You start screaming the tune of 'We Are The Champions' to distract the mermaid. It serenades her into a deep slumber. You STEAL a DVD, Indiana Jones style. However, ");
                    System.out.println("you have not brought anything to replace the DVD with. The entire cave begins to rumble, and you are suddenly about to be crushed by a rolling boulder, also ");
                    System.out.println("Indiana Jones style! The only difference is you get crushed by the boulder, THE END.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                }
                ////Third Choice 6 "guess"
                else if (C3c.equalsIgnoreCase("guess")) {
                    System.out.println("Please insert your guess into me! (Number)");
                    int num = k.nextInt();
                    double bignum = Math.PI * Math.pow(num, 2);
                    System.out.println("'Hmmm my guess is " + num + "!'. 'So close!' says the mermaid. But the answer is actually " + bignum + "! I'm sorry but you aren't qualified to touch my DVD's.'");
                    System.out.println(" You gaze at the wet pile of DVD's and cry tears of soy. When it hits the water, you realize what your life has become. Seeing that murky reflection fills ");
                    System.out.println("you with sadness. GAME OVER.");
                    System.out.println("Thank you for playing my adventure, press run to play again.");
                } else {
                    System.out.println("That is not an option. Please run again.");
                }

            }
        }

I hope this is what you wanted.


来源: stackexchange

问:
Is it normal to have a list of objects in an object?
I'm new to OO design, and I wondering whether it is typical to have designs where objects contain lists of other objects. An example is below:

```<code>// Person object containing a list of phone numbers
public class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Phone> Contacts { get; set; }

    public void AddPhoneNumber(Phone phone)
    {
        Contacts.Add(phoneNumber);
    }
}

// Phone object
public class Phone
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Number { get; set; }
}

// Example code to establish an object:
Person p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Smith";
p1.AddPhoneNumber(new Phone() { Number = "555957000" });
p1.AddPhoneNumber(new Phone() { Number = "555579561" });
</code>```

Is there a better way to structure this that simplifies the design and allows easier access to the data? Thanks!

答:
There's nothing wrong with your code. It's perfectly valid to have a list of objects within an object.

Though adding a string to your List of Phone objects will throw an error.

You can add a phone number like so:

```<code>Person p1 = new Person();
p1.Contacts.Add(new Phone() { Number = "555579561" });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to OO design, and I wondering whether it is typical to have designs where objects contain lists of other objects. An example is below:

// Person object containing a list of phone numbers
public class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Phone> Contacts { get; set; }

    public void AddPhoneNumber(Phone phone)
    {
        Contacts.Add(phoneNumber);
    }
}

// Phone object
public class Phone
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Number { get; set; }
}

// Example code to establish an object:
Person p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Smith";
p1.AddPhoneNumber(new Phone() { Number = "555957000" });
p1.AddPhoneNumber(new Phone() { Number = "555579561" });

Is there a better way to structure this that simplifies the design and allows easier access to the data? Thanks!

Body:
There's nothing wrong with your code. It's perfectly valid to have a list of objects within an object.

Though adding a string to your List of Phone objects will throw an error.

You can add a phone number like so:

Person p1 = new Person();
p1.Contacts.Add(new Phone() { Number = "555579561" });


问:
OpenCV2 Python createBackgroundSubtractor module not found
I am trying to use cv2.createBackgroundSubtractorMOG2 () method in Python. I have tried both on my Mac and on my Raspberry Pi, and get the same error when running the following line of code:

```<code>fgbg = cv2.createBackgroundSubtractorMOG2()
</code>```

The code I am using is taken from https://github.com/abidrahmank/OpenCV2-Python-Tutorials/blob/master/source/py_tutorials/py_video/py_bg_subtraction/py_bg_subtraction.rst

I get the following error when running this code:

fgbg = cv2.createBackgroundSubtractorMOG2()
  AttributeError: 'module' object has no attribute 'createBackgroundSubtractorMOG2'

I can't seem to use any of the createBackgroundSubtractor methods.

I have been trying to solve this for the past day, but I have had no luck searching online, as there is limited support for cv2 on Python.

Thanks in advance

答:
I'm using </p>

```<code>>>> import cv2
>>> cv2.__version__
>>> 3.2.0
</code>```

<p>and python 2.7.12. While I tried to use cv2.createBackgroundSubtractorMOG() I received the same error message (also tried without "create..."). But I was surprised when I discovered cv2.createBackgroundSubtractorKNN() with the same functionality instead ... and the test code works :)
2 days I was confused and couldn't find where the problem is. </p>

Body:
I am trying to use cv2.createBackgroundSubtractorMOG2 () method in Python. I have tried both on my Mac and on my Raspberry Pi, and get the same error when running the following line of code:

fgbg = cv2.createBackgroundSubtractorMOG2()

The code I am using is taken from https://github.com/abidrahmank/OpenCV2-Python-Tutorials/blob/master/source/py_tutorials/py_video/py_bg_subtraction/py_bg_subtraction.rst

I get the following error when running this code:

fgbg = cv2.createBackgroundSubtractorMOG2()
  AttributeError: 'module' object has no attribute 'createBackgroundSubtractorMOG2'

I can't seem to use any of the createBackgroundSubtractor methods.

I have been trying to solve this for the past day, but I have had no luck searching online, as there is limited support for cv2 on Python.

Thanks in advance

Body:
I'm using

>>> import cv2
>>> cv2.__version__
>>> 3.2.0

and python 2.7.12. While I tried to use cv2.createBackgroundSubtractorMOG() I received the same error message (also tried without "create..."). But I was surprised when I discovered cv2.createBackgroundSubtractorKNN() with the same functionality instead ... and the test code works :)
2 days I was confused and couldn't find where the problem is.


问:
EJS Tags with ChartJS?
Is it possible to use EJS tags to add data to a graph? Here is my current graph's data:

```<code>var canvas = document.getElementById('myChart');
var data = {
    labels: ["One", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [10, 20, 81, 56, 55, 40],
        }
    ]
};
</code>```

I'm wanting to do something like this:

```<code>labels: ["<%= currentUser.datapoint1 %>", "<%= currentUser.datapoint2 %>", "<%= currentUser.datapoint3 %>"]

data: [<%= currentUser.datapoint10 %>, <%= currentUser.datapoint11 %>]
</code>```

How would I accomplish using EJS tags to populate the graphs data? (NOTE: The EJS tag info would have already been saved the user before the chart needs to be generated)

答:
Yes, you can use EJS tags or any other similar tag used across the various view javascript frameworks (e.g. handlebars, spacebars in meteor, ejs, etc.).  Chart.js is initialized at runtime, so it has no knowledge of how the data made its way into the file (e.g. it doesn't know...nor does it care...that your javascript was pre-processed and generated).

The format of the tag itself just has to do with the variables in which you stored your data.  I would recommend storing your labels and data in arrays and using JSON.stringify().

```<code>// defined in your app
var labels = ['label 1', 'label 2', ...];
var data = [datapoint1, datapoint2, ...];

// in your EJS file.
var canvas = document.getElementById('myChart');
var data = {
  labels: <%- JSON.stringify(labels); %>,
  datasets: [
    {
      label: "My First dataset",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: <%- JSON.stringify(data); %>,
    }
  ]
};
</code>```

Title: EJS Tags with ChartJS?

Body:
Is it possible to use EJS tags to add data to a graph? Here is my current graph's data:

var canvas = document.getElementById('myChart');
var data = {
    labels: ["One", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [10, 20, 81, 56, 55, 40],
        }
    ]
};

I'm wanting to do something like this:

labels: ["<%= currentUser.datapoint1 %>", "<%= currentUser.datapoint2 %>", "<%= currentUser.datapoint3 %>"]

data: [<%= currentUser.datapoint10 %>, <%= currentUser.datapoint11 %>]

How would I accomplish using EJS tags to populate the graphs data? (NOTE: The EJS tag info would have already been saved the user before the chart needs to be generated)

Body:
Yes, you can use EJS tags or any other similar tag used across the various view javascript frameworks (e.g. handlebars, spacebars in meteor, ejs, etc.).  Chart.js is initialized at runtime, so it has no knowledge of how the data made its way into the file (e.g. it doesn't know...nor does it care...that your javascript was pre-processed and generated).

The format of the tag itself just has to do with the variables in which you stored your data.  I would recommend storing your labels and data in arrays and using JSON.stringify().

// defined in your app
var labels = ['label 1', 'label 2', ...];
var data = [datapoint1, datapoint2, ...];

// in your EJS file.
var canvas = document.getElementById('myChart');
var data = {
  labels: <%- JSON.stringify(labels); %>,
  datasets: [
    {
      label: "My First dataset",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: <%- JSON.stringify(data); %>,
    }
  ]
};


问:
Error in program when parsing negative integers into an array
I am having a strange issue with one of my assignments. I am attempting to take integers from user input and store them in an array. After that, four recursive methods will be run on them to find different characteristics of those numbers. However, whenever I attempt to run the program with a negative integer in any of the indexes the program stops responding.

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];
    InputStreamReader inRead = new InputStreamReader(System.in);
    BufferedReader buffRead = new BufferedReader(inRead);
    String line = buffRead.readLine();

    try {
        while (!line.equals("0") && index < 100) {
            numbers[index] = Integer.parseInt(line);
            index++;
            line = buffRead.readLine();

        }
    } catch (IOException exception) {
        System.out.println("Array index out of bound");
    }
`       int min = findMin(numbers, 0, numbers.length - 1);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println("The maximum number among numbers that are less than the first number is " + maxLessThanFirst);

    }

    public static int findMin(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            return numbers[startIndex];
        } else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
            return findMin(numbers, startIndex, endIndex - 1);
        } else {
            return numbers[endIndex];
        }

    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

}
</code>```

This is the only relevant section of code that is necessary to understand the problem, I believe. If additional code is needed just ask. Thank you!

答:
Your findMin method is doubly recursive:

```<code>public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex) {
        return numbers[startIndex];
        // in the next line, we recurse looking for the minimum
    } else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
        // we've found the minimum, but now we must recurse again to get it!
        return findMin(numbers, startIndex, endIndex - 1);
    } else {
        return numbers[endIndex];
    }
}
</code>```

This transforms what should be a linear algorithm into an exponential one. If you log each time findMin is entered, you will find it increases rapidly with the size of the array. Experimentation shows that it is called 2^(x-1) + 2^(x-2) - 1 times, where x is the length of the array.

So if you had an array of size 10, it would be called 767 times. For an array of size 20, it would be called 786,431 times. Size 30, 25,165,823 times. Size 100 yields:

950,737,950,171,172,051,122,527,404,031 calls (950 octillion, 9.5 x 10^29).

Your program will not crash with a StackOverflowError because at no time does the stack depth exceed roughly the length of the array (plus one for the main), but it will take longer than the lifespan of the universe to run.

Changing findMin to this:

```<code>public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex) {
        return numbers[startIndex];
    }
    // there's no need for an else since the if ended with a return
    int r = findMin(numbers, startIndex, endIndex - 1); // only recurse once
    if (r < numbers[endIndex]) {
        // we've found the minimum, return it without recursing again
        return r;
    }
    // again, no need for else, here
    return numbers[endIndex];
}
</code>```

Now the algorithm only takes 20 calls for an array of size 20, 50 for size 50, 100 for size 100. The fact that you had already called findMin recursively to get the value to compare but were then calling it again to get the same value to return should have been a red flag. In many cases, such unnecessary repetition would merely be a minor annoyance; in this case, it was catastrophic.

Oh, I forgot to mention. The reason entering a negative number triggered the problem: Presumably, you don't always type 100 numbers in. I never did when I tried your program. It's too boring, and you can just end the list by entering a zero. When you allocate the array:

```<code>int[] numbers = new int[100];
</code>```

The array is filled with zeros. So, if you enter ten numbers, the rest of the array will be zeros, and when we get to this line in the first call to findMin:

```<code>    if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex])
</code>```

The number at the end will be zero, which is also the min. So we only recurse once, not twice. That will happen for most of the recursive calls, too; it will happen for all the ones at the long tail of zeros at the end of the array. It will only be when we get down into the entries where the user has actually entered a value where we will see the doubly-recursive behavior. If the user only enters about 10 numbers, we're safe.

But if the user enters even a single negative number, then that becomes the minimum and the zeros don't protect us. We hit the double recursion on every call, except for the one where numbers[endIndex] holds that negative number. Come to think of it, the reason I got 2^(x-1) + 2^(x-2) - 1 instead of just 2^x - 1 is because I always put the negative number in the second position in the array. So, depending on where the minimum value is, you could get performance better, or even worse, than what I describe above.

Body:
I am having a strange issue with one of my assignments. I am attempting to take integers from user input and store them in an array. After that, four recursive methods will be run on them to find different characteristics of those numbers. However, whenever I attempt to run the program with a negative integer in any of the indexes the program stops responding.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];
    InputStreamReader inRead = new InputStreamReader(System.in);
    BufferedReader buffRead = new BufferedReader(inRead);
    String line = buffRead.readLine();

    try {
        while (!line.equals("0") && index < 100) {
            numbers[index] = Integer.parseInt(line);
            index++;
            line = buffRead.readLine();

        }
    } catch (IOException exception) {
        System.out.println("Array index out of bound");
    }
`       int min = findMin(numbers, 0, numbers.length - 1);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println("The maximum number among numbers that are less than the first number is " + maxLessThanFirst);

    }

    public static int findMin(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            return numbers[startIndex];
        } else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
            return findMin(numbers, startIndex, endIndex - 1);
        } else {
            return numbers[endIndex];
        }

    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

}

This is the only relevant section of code that is necessary to understand the problem, I believe. If additional code is needed just ask. Thank you!

Body:
Your findMin method is doubly recursive:

public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex) {
        return numbers[startIndex];
        // in the next line, we recurse looking for the minimum
    } else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
        // we've found the minimum, but now we must recurse again to get it!
        return findMin(numbers, startIndex, endIndex - 1);
    } else {
        return numbers[endIndex];
    }
}

This transforms what should be a linear algorithm into an exponential one. If you log each time findMin is entered, you will find it increases rapidly with the size of the array. Experimentation shows that it is called 2^(x-1) + 2^(x-2) - 1 times, where x is the length of the array.

So if you had an array of size 10, it would be called 767 times. For an array of size 20, it would be called 786,431 times. Size 30, 25,165,823 times. Size 100 yields:

950,737,950,171,172,051,122,527,404,031 calls (950 octillion, 9.5 x 10^29).

Your program will not crash with a StackOverflowError because at no time does the stack depth exceed roughly the length of the array (plus one for the main), but it will take longer than the lifespan of the universe to run.

Changing findMin to this:

public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex) {
        return numbers[startIndex];
    }
    // there's no need for an else since the if ended with a return
    int r = findMin(numbers, startIndex, endIndex - 1); // only recurse once
    if (r < numbers[endIndex]) {
        // we've found the minimum, return it without recursing again
        return r;
    }
    // again, no need for else, here
    return numbers[endIndex];
}

Now the algorithm only takes 20 calls for an array of size 20, 50 for size 50, 100 for size 100. The fact that you had already called findMin recursively to get the value to compare but were then calling it again to get the same value to return should have been a red flag. In many cases, such unnecessary repetition would merely be a minor annoyance; in this case, it was catastrophic.

Oh, I forgot to mention. The reason entering a negative number triggered the problem: Presumably, you don't always type 100 numbers in. I never did when I tried your program. It's too boring, and you can just end the list by entering a zero. When you allocate the array:

int[] numbers = new int[100];

The array is filled with zeros. So, if you enter ten numbers, the rest of the array will be zeros, and when we get to this line in the first call to findMin:

    if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex])

The number at the end will be zero, which is also the min. So we only recurse once, not twice. That will happen for most of the recursive calls, too; it will happen for all the ones at the long tail of zeros at the end of the array. It will only be when we get down into the entries where the user has actually entered a value where we will see the doubly-recursive behavior. If the user only enters about 10 numbers, we're safe.

But if the user enters even a single negative number, then that becomes the minimum and the zeros don't protect us. We hit the double recursion on every call, except for the one where numbers[endIndex] holds that negative number. Come to think of it, the reason I got 2^(x-1) + 2^(x-2) - 1 instead of just 2^x - 1 is because I always put the negative number in the second position in the array. So, depending on where the minimum value is, you could get performance better, or even worse, than what I describe above.


问:
How to place widgets next to each other?
I am building a simple GUI program to manage priorities. I am having trouble placing button widgets next to each other. It is somehow logical to me that if I want three buttons (Add, Remove, Edit) to place next to each other, I should use column = 0 for Add, column = 1 for Remove and column = 2 for Edit. Anyway, this is what I get:

Here is the createWidgets function:

```<code>def createWidgets(self):

    listBox = Listbox(width = 30).grid(row=1, column = 0)

    Button(self.root,
                text = "Add",
                command = self.addItem).grid(row = 2, column = 1, sticky = W)

    Button(self.root,
           text="Remove",
           command = self.removeItem).grid(row = 2, column = 2, sticky = W)

    Button(self.root,
        text="Edit",
        command = self.editItem).grid(row = 2, column = 3, sticky = W)

    textBox = Text(height = 10, width = 30).grid(row = 3)
</code>```

答:
My advice is to break your UI down into regions, and manage each region independently. It's much easier than trying to cram everything into one big grid, especially when you have widgets with very different sizes.

Create three frames: one for the top, one for the group of buttons, and one for the bottom. You can then use pack to place them top-to-bottom:

```<code>top_frame.pack(side="top", fill="both", expand=True)
button_frame.pack(side="top", fill="x")
bottom_frame.pack(side="bottom", fill="both", expand=True)
</code>```

(the use of expand depends on if you want that frame to expand when the window is made larger)

Once you've done that, you can tackle each region separately. For example, you can make the buttons children of the button frame, and use .pack(side='left') to get them to be left-aligned. The other widgets can also use pack if they are the only widgets in each of the other frames, or you can use grid.

You will find that just a few minutes organizing your UI before starting to code will make a big difference in how easy it is to create and maintain.

Example:

```<code>def createWidgets(self):
    topFrame = tk.Frame(self)
    buttonFrame = tk.Frame(self)
    bottomFrame = tk.Frame(self)

    topFrame.pack(side="top", fill="both", expand=True)
    buttonFrame.pack(side="top", fill="x")
    bottomFrame.pack(side="bottom", fill="both", expand=True)

    listBox = tk.Listbox(topFrame, width=30)
    listBox.pack(side="top", fill="both", expand=True)

    tk.Button(buttonFrame, text="Add").pack(side="left")
    tk.Button(buttonFrame, text="Remove").pack(side="left")
    tk.Button(buttonFrame, text="Edit").pack(side="left")

    textBox = tk.Text(bottomFrame, height=10, width=30)
    textBox.pack(fill="both", expand=True)
</code>```

Body:
I am building a simple GUI program to manage priorities. I am having trouble placing button widgets next to each other. It is somehow logical to me that if I want three buttons (Add, Remove, Edit) to place next to each other, I should use column = 0 for Add, column = 1 for Remove and column = 2 for Edit. Anyway, this is what I get:

Here is the createWidgets function:

def createWidgets(self):

    listBox = Listbox(width = 30).grid(row=1, column = 0)

    Button(self.root,
                text = "Add",
                command = self.addItem).grid(row = 2, column = 1, sticky = W)

    Button(self.root,
           text="Remove",
           command = self.removeItem).grid(row = 2, column = 2, sticky = W)

    Button(self.root,
        text="Edit",
        command = self.editItem).grid(row = 2, column = 3, sticky = W)

    textBox = Text(height = 10, width = 30).grid(row = 3)

Body:
My advice is to break your UI down into regions, and manage each region independently. It's much easier than trying to cram everything into one big grid, especially when you have widgets with very different sizes.

Create three frames: one for the top, one for the group of buttons, and one for the bottom. You can then use pack to place them top-to-bottom:

top_frame.pack(side="top", fill="both", expand=True)
button_frame.pack(side="top", fill="x")
bottom_frame.pack(side="bottom", fill="both", expand=True)

(the use of expand depends on if you want that frame to expand when the window is made larger)

Once you've done that, you can tackle each region separately. For example, you can make the buttons children of the button frame, and use .pack(side='left') to get them to be left-aligned. The other widgets can also use pack if they are the only widgets in each of the other frames, or you can use grid.

You will find that just a few minutes organizing your UI before starting to code will make a big difference in how easy it is to create and maintain.

Example:

def createWidgets(self):
    topFrame = tk.Frame(self)
    buttonFrame = tk.Frame(self)
    bottomFrame = tk.Frame(self)

    topFrame.pack(side="top", fill="both", expand=True)
    buttonFrame.pack(side="top", fill="x")
    bottomFrame.pack(side="bottom", fill="both", expand=True)

    listBox = tk.Listbox(topFrame, width=30)
    listBox.pack(side="top", fill="both", expand=True)

    tk.Button(buttonFrame, text="Add").pack(side="left")
    tk.Button(buttonFrame, text="Remove").pack(side="left")
    tk.Button(buttonFrame, text="Edit").pack(side="left")

    textBox = tk.Text(bottomFrame, height=10, width=30)
    textBox.pack(fill="both", expand=True)


问:
Python math range error
I'm getting an error when trying to calculate a very large number in Python. Here is my code:

```<code># Where fourthNumber = 2790
# and dee = 413
emm = math.pow(fourthNumber, dee)
</code>```

An my error is:

```<code>line 44, in <module>
    emm = math.pow(fourthNumber, dee)
OverflowError: math range error
</code>```

Is there a way around this error? I thought Python could handle arbitrarily large numbers? Or am I wrong? Any help is appreciated. Thanks!

答:
You can handle arbitrarily large integer numbers; math.pow operates of floating-point numbers.

2790 ** 413 > 1000 ** 413 = 1e+1239, way above the floating-point range of around 1e+308.

Use ** to stay within integers domain, and get your huge integer number.

Title: Python math range error

Body:
I'm getting an error when trying to calculate a very large number in Python. Here is my code:

# Where fourthNumber = 2790
# and dee = 413
emm = math.pow(fourthNumber, dee)

An my error is:

line 44, in <module>
    emm = math.pow(fourthNumber, dee)
OverflowError: math range error

Is there a way around this error? I thought Python could handle arbitrarily large numbers? Or am I wrong? Any help is appreciated. Thanks!


问:
Execute function according to time
I'm trying to create a way for every minute the execute_func function to be executed.

I have tried to loop in minutes, however the function is never executed, below the function

```<code>void main(void) {
    time_t timer;
    struct tm* tmr;

    timer = time(NULL);
    tmr = localtime(&timer);

        if (tmr->tm_min == 1)
            execute_func();
    }
    return;
}
</code>```

答:
How about your startup routine?
I mean your main function invokes execute_func, and function execute_func invokes main again. That's so strange.

If you just wanna do some periodic job. You can put these job into another no-main function. And you can use any delay function at the same time.

```<code>void PeriodicJob()
{
  xxx;
}

main()
{
  for (;;)
  {
    Sleep(60000); // You can use this function on windows platform. Notice that you must include windows.h first.
    // Or you can write your own delay function too.
    PeriodicJob();
  }
  return 0;
}
</code>```

If you want to periodic run a program. That's your operating system's job. Try to use task schedule on your OS.

Title: Execute function according to time

Body:
I'm trying to create a way for every minute the execute_func function to be executed.

I have tried to loop in minutes, however the function is never executed, below the function

void main(void) {
    time_t timer;
    struct tm* tmr;

    timer = time(NULL);
    tmr = localtime(&timer);

        if (tmr->tm_min == 1)
            execute_func();
    }
    return;
}

Body:
How about your startup routine?
I mean your main function invokes execute_func, and function execute_func invokes main again. That's so strange.

If you just wanna do some periodic job. You can put these job into another no-main function. And you can use any delay function at the same time.

void PeriodicJob()
{
  xxx;
}

main()
{
  for (;;)
  {
    Sleep(60000); // You can use this function on windows platform. Notice that you must include windows.h first.
    // Or you can write your own delay function too.
    PeriodicJob();
  }
  return 0;
}

If you want to periodic run a program. That's your operating system's job. Try to use task schedule on your OS.


问:
Java User Input array is only capturing 3 integers instead of five
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0"  which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.</p>

```<code>import java.util.Scanner;

public class ArrayReverse {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in); // scanner for input
        final int NUM_VALS = 5; // number on int user able to enter
        int[] userNum = new int[NUM_VALS]; // user integers storage
        int j = 0;
        int i = 0;

        System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int

        for (j = 0; j < NUM_VALS; j++) {
            System.out.print("You entered: ");
            System.out.println(userNum[i]);
            ++j;
        }
        System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
        for (j = NUM_VALS - 1; j >= 0; j--) {
            System.out.print(userNum[i] + " ");
        }
    }
}
</code>```

答:
I have provided you with a solution. This is a clean way of doing it.

nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.

```<code> public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    List<Integer> input = new ArrayList<Integer>();

    //Simple loop that will read 5 user inputs
    //and add them to the input list
    for(int i = 0; i < 5; i++){
        input.add(scanner.nextInt());
    }

    //print the 5 values
    for(Integer val : input){
        System.out.println(val);
    }

    //reverse the 5 values
    Collections.reverse(input);

    //print the 5 values again, but they are now reversed
    for(Integer val : input){
        System.out.println(val);
    }
}
</code>```

Body:
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0"  which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.

import java.util.Scanner;

public class ArrayReverse {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in); // scanner for input
        final int NUM_VALS = 5; // number on int user able to enter
        int[] userNum = new int[NUM_VALS]; // user integers storage
        int j = 0;
        int i = 0;

        System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int

        for (j = 0; j < NUM_VALS; j++) {
            System.out.print("You entered: ");
            System.out.println(userNum[i]);
            ++j;
        }
        System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
        for (j = NUM_VALS - 1; j >= 0; j--) {
            System.out.print(userNum[i] + " ");
        }
    }
}

Body:
I have provided you with a solution. This is a clean way of doing it.

nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.

 public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    List<Integer> input = new ArrayList<Integer>();

    //Simple loop that will read 5 user inputs
    //and add them to the input list
    for(int i = 0; i < 5; i++){
        input.add(scanner.nextInt());
    }

    //print the 5 values
    for(Integer val : input){
        System.out.println(val);
    }

    //reverse the 5 values
    Collections.reverse(input);

    //print the 5 values again, but they are now reversed
    for(Integer val : input){
        System.out.println(val);
    }
}


问:
File not reading in selenium - maven framewaork
I tried to create a quick framework. in that I created below-mentioned classes:

Config file(All browsers path)

configDataProvider java class(reads the above file)

BrowserFactory class(has firefox browser object)

configDataProviderTest class(access data from dconfigDataProvider class)

now its not reading the paths mentioned in config.properties file.

I have provided all correct path and attached screenshots:

答:
Looks like a problem is at your ConfigDataProvider class.

Firstly, you using Maven for building your project. Maven has defined project structure for code sources and for resources:

```<code>/src/main/java
/src/main/resorces
</code>```

Thus, much better to put your .properties file there.

Second, you don't need to set the full path to your config file.

Relative path will be just enough. Something like below:

```<code>public class PropertiesFileHandler {
    private static Logger log = Logger.getLogger(PropertiesFileHandler.class);

    public static final String CONFIG_PROPERTIES = "src/main/resources/config.properties";
    public static final String KEY = "browser.type";

    public static BrowserType readBrowserType() {
        BrowserType browserType = null;
        Properties properties = new Properties();

        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(CONFIG_PROPERTIES))) {
            properties.load(inputStream);
            browserType = Enum.valueOf(BrowserType.class, properties.getProperty(KEY));
        } catch (FileNotFoundException e) {
            log.error("Properties file wasn't found - " + e);
        } catch (IOException e) {
            log.error("Problem with reading properties file - " + e);
        }
        return browserType;
    }
}
</code>```

Lastly, if you are building framework you don't need to put everything under src/main/test. This path specifies tests with future possibilities to be executed with maven default lifecycle - mvn test.

The core of your framework can look like:

Body:
Looks like a problem is at your ConfigDataProvider class.

Firstly, you using Maven for building your project. Maven has defined project structure for code sources and for resources:

/src/main/java
/src/main/resorces

Thus, much better to put your .properties file there.

Second, you don't need to set the full path to your config file.

Relative path will be just enough. Something like below:

public class PropertiesFileHandler {
    private static Logger log = Logger.getLogger(PropertiesFileHandler.class);

    public static final String CONFIG_PROPERTIES = "src/main/resources/config.properties";
    public static final String KEY = "browser.type";

    public static BrowserType readBrowserType() {
        BrowserType browserType = null;
        Properties properties = new Properties();

        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(CONFIG_PROPERTIES))) {
            properties.load(inputStream);
            browserType = Enum.valueOf(BrowserType.class, properties.getProperty(KEY));
        } catch (FileNotFoundException e) {
            log.error("Properties file wasn't found - " + e);
        } catch (IOException e) {
            log.error("Problem with reading properties file - " + e);
        }
        return browserType;
    }
}

Lastly, if you are building framework you don't need to put everything under src/main/test. This path specifies tests with future possibilities to be executed with maven default lifecycle - mvn test.

The core of your framework can look like:


问:
How to hint use of UIView subclass for compiler
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

```<code>- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}
</code>```

This is fine until I call a method of UIWebView's. For example...

```<code>[self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...leads to a compiler warning...

```<code>warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'
</code>```

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

```<code>[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

```<code>warning: property 'view' type does not match super class 'UIViewController' property type
</code>```

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...

答:
Since it's a subclass, you can override the view property/method to be a UIWebView. Since a UIWebView is a subclass of UIView, and you're the only user of your subclass, this should be completely safe.

```<code>@interface MyAbstractViewController : UIViewController {
    UIWebView *_webView;
}
@property (nonatomic, retain) UIWebView *view;
@end

@implementation MyAbstractViewController
@dynamic view;
- (void)setView:(UIWebView *)webView {
  [super setView:webView];
  _webView = webView;
}

- (UIWebView *)view {
  return _webView;
}
@end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}

This is fine until I call a method of UIWebView's. For example...

[self.view loadHTMLString:HTMLString baseURL:baseURL];

...leads to a compiler warning...

warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

warning: property 'view' type does not match super class 'UIViewController' property type

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...

Body:
Since it's a subclass, you can override the view property/method to be a UIWebView. Since a UIWebView is a subclass of UIView, and you're the only user of your subclass, this should be completely safe.

@interface MyAbstractViewController : UIViewController {
    UIWebView *_webView;
}
@property (nonatomic, retain) UIWebView *view;
@end

@implementation MyAbstractViewController
@dynamic view;
- (void)setView:(UIWebView *)webView {
  [super setView:webView];
  _webView = webView;
}

- (UIWebView *)view {
  return _webView;
}
@end