Eclipse android IndexOutOfBounds - java
currently i dont know what im doing wrong here is my sample code please help me
Problem:
02-28 03:41:51.750: E/AndroidRuntime(8431): java.lang.IndexOutOfBoundsException: Invalid index 95, size is 90
02-28 03:41:51.750: E/AndroidRuntime(8431): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
02-28 03:41:51.750: E/AndroidRuntime(8431): at com.example.finalpro.ThirdQuiz$1.onClick(ThirdQuiz.java:248
02-28 03:41:51.750: E/AndroidRuntime(8431): at com.example.finalpro.ThirdQuiz.showNextQuiz(ThirdQuiz.java:194)
02-28 03:41:51.750: E/AndroidRuntime(8431): at java.util.ArrayList.get(ArrayList.java:308)
Now my Java :
public class ThirdQuiz extends ActionBarActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private Button answerBtn3;
private Button answerBtn4;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 25;
int quizCategory = 0;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {"Country", "Right Answer", "Choice1", "Choice2", "Choice3"}
{"Feed me and I live, yet give me a drink and I die", "Fire"," Ice ","Hot","Cold"} ,
{"I fly without wings, I cry without eyes. What am I", " Clouds"," Rain ","Rainbow ","Sun"},
{"You can see me in water, but I never get wet. What am I?", " A reflection"," Mirror","Wall","BlackBoard"},
{"What belongs to you but others use it more than you do?", " Your name"," Your NickName","Your LastName"," Your UserName"},
{"What 4-letter word can be written forward, backward or upside down, and can still be read from left to right?", " NOON"," Moon","Four","Dead"},
{"What runs around the whole yard without moving?", " A fence"," Wall","Board"," Table"},
{"What kind of table can you eat?", " Vegetable"," Meat","Fruits"," Chicken"},
{"What's orange and sounds like a parrot?", " A carrot","Banana","Meat"," Potato"},
{"Which is the most curious letter?", " Y?","A?","B?"," X?"},
{"What does the big tomato say to the small tomato?", " Ketchup","Mang Thomas","Datu Puti","Silver Swan"},
{"What begins with T, ends with T and has T in it?", " Teapot","Team Potatot","Tilt","Talt"},
{"People buy me to eat, but never eat me. What am I?", "Plates and cuttlery","My Friends","Food","Junk Food"},
{"The more you take, the more you leave behind. What am I?", "Footsteps","Slow Motion","At the back","Hiding"},
{"A blue house has blue bricks; a yellow house has a yellow bricks. What is a green house made of?", "Glass","Grass","Wall","Door"},
{"Railroad crossing without any cars. Can you spell that without any R’s?", "Thats","Why","Where","How"},
{"What kind of dog keeps the best time?", "Watchdog","Watch Anime","Watch Cartoons","Watch Actions"},
{"You can do this with your friends. You can do this with your nose. But don't do it with your friend's nose!", "Pick","Touch","Watch","Move"},
{"What is it something that you always have but you always leave behind?", "Fingerprints","Footprints","Faceprints","Bodyprints"},
{"How can you physically stand behind your father while he is standing behind you?", "Stand back to back","Following me","Stay","Istalker"},
{"There was a plane crash every single person died. Who survived?", "Married couples","Single Parents","Single","RelationShip"},
{"What does no man want, yet no man want to lose?", "His job","His Family","Important to me"," His RelationShip"},
{"This company makes billions of dollars selling Windows.", "Microsoft","Google","PowerPoint"," Microsoft Office"},
{"What language does a billboard speak?", " Sign language"," Rain ","Rainbow ","Sun"} ,
{"What does this mean? Wondealicerland", "Alice in wonderland"," Batman ","Superman ","SpiderMan"} ,
{"Which ring is square?", "A boxing ring","Basketball Court ","Volleyball Court ","Class Room"} ,
{"What US state is surrounded by the most water?", "Hawaii"," Canada ","America ","Hongkong"} ,
{"Three times what number is no larger than two times that same number?", "0"," 2 ","4","6"} ,
{"Which of Santa's reindeer can you see in outer space?", "Comet"," Asteroid ","Meteors","Planet"} ,
{"What gets tighter when stretched?", "A budget"," Exercise ","Hungry","Waster"} ,
{"When set loose I fly away, Never so cursed As when I go astray.", "A fart"," hungry ","Hurry","Sleepy"} ,
{"Everyone has me but nobody can lose me. What am I?", "A shadow"," A friend ","Family","Enemy"} ,
{"Fashions change but what can a person wear that is never out of style?", "A smile"," Sad ","Angry","Ugly"},
{"A kind of tree can you carry in your hand?", "A palm"," Foot ","Ears","Touch"} ,
{"What can you catch but not throw?", "A cold"," Sad ","Angry","Ugly"} ,
{"What sits in a corner while travelling all around the world?", "Stamp"," Hi ","Signature","Messages"} ,
{"I'm flat when I'm new. I'm fat when you use me. I release my gas when something sharp touches me. What am I?", "A balloon"," Mirror","Picture","Selfie"},
{"I am a king who’s good at measuring stuff. What am I?", "Ruler"," Ball Pen ","Eraser","Pencil"},
{"Which word contains 26 letters but only three syllables?", "Alphabet"," Letters ","Spelling","Direction"} ,
{"What can you hear but not touch or see and yet control?", "Your voice"," Moving ","Stay","Go away"} ,
{"What did the thief get for stealing the calendar?", "12 Months"," 10 Months ","11 Months","8 Months"} ,
{"Before Mt. Everest was discovered as the highest mountain in the world, which mountain was the highest?", "Mt Everest"," Mt k2 ","Mt Makalu","Mr Panaslu"} ,
{"howers bring may flowers, what do may flowers bring?", "Pilgrims"," Ball Pen ","Eraser","Pencil"} ,
{"What did Adam say the day before Christmas?", "It's Christmas, Eve!"," New Year ","Birthday","Reunion"} ,
{"What kind of fish chases a mouse?", "Catfish"," Dog ","Horse","Bird"} ,
{"What has four legs, but can't walk?", "A table"," Board ","Chair","Pencil"} ,
{"What is always slow to come, but never actually happens?", "Tomorrow"," Yesterday ","Later","After Noon"} ,
{"If you blow past your destination, you'll have to throw your car into this."," Reverse ","Force","Move","Walk"},
{"What has a mouth but can't chew?", "River"," Road ","Air","Inside"} ,
{"David's father has three sons: Snap, Crackle, and ?","David"," Angel ","Mico","Klein"} ,
{"What has a ring, but no finger?", "Phone"," Laptop ","Computer","Tablet"},
{"You play with me at night before going to sleep. You can’t get caught fiddling with me at work. You only let a select few people touch me. What am I?","Phone","pillow","blanket","toys"},
{" What’s a four-letter word that ends in “k” and means the same as intercourse?","Talk","seek","peek","weak"},
{" I start with a “v” and every woman has one. She can even use me to get what she wants. What am I?","voice.","vase","vein","verse"},
{" I come in a lot of different sizes. Sometimes, I drip a little. If you blow me, it feels really good. What am I?","nose.","mout","ears","eyes"},
{".What’s in a man’s pants that you won’t find in a girl’s dress?","Pockets","stripes","buttons","zipper"},
{"You stick your poles inside me. You tie me down to get me up. I get wet before you do. What am I?","tent.","house","barbique","rope"},
{"What’s long and hard and has cum in it?","cucumber","egg plant","bittergourd","bottlegourd"},
{" If I miss, I might hit your bush. It’s my job to stuff your box. When I come, it’s news. What am I?","newspaperboy","reporter","tv","radio"},
{" What four-letter word begins with “f” and ends with “k,” and if you can’t get it you can always just use your hands?"," fork","fowk","feek","flak"},
{" All day long it’s in and out. I discharge loads from my shaft. Both men and women go down on me. What am I?","elevator","escalator","stairs","ladders"},
{"I’m spread out before being eaten. Your tongue gets me off. People sometimes lick my nuts. What am I?","Peanut butter.","jelly","ketchup","mayonnaise"},
{"Arnold Schwarzenegger’s is really long. Michael J. Fox’s is short. Daffy Duck’s isn’t human. Madonna doesn’t have one. What am I?","last name","first name","middle name","nickname"},
{"What is hard and hairy on the outside, soft and wet on the inside? The word begins with “c,” ends in “t,”.","coconut.","coat","cat","carrot"},
{"I start with a “p” and ends with “n” and I’m a major player in the film industry. What am I?","popcorn","person","penguin","putin"},
{"My business is briefs. I’m a cunning linguist. I plead and plead for it regularly. What am I?","lawyer","judge","police","governor"},
{"You get a lot of it if you’re powerful and successful, but significantly less when you’re just starting out. You sometimes do it with yourself, but it’s a lot better when you do it with another person. What am I talking about?","email","chat","text","mail"},
{"I have a stiff shaft. My tip penetrates. I come with a quiver. What am I?","arrow","javellin","bullet","rocket"},
{"I go in hard but come out soft, and I never mind if you want to blow me. What am I?","bubblegum","clay","paper","cement"},
{"What does a dog do that a man steps into?","pants","shorts","shirt","underwear"},
{"I’m great for protection. You use your fingers to get me off. What am I?","gloves","cloth","shield","ring"},
{"What gets longer if pulled, fits snugly between breasts, slides neatly into a hole, chokes people when used incorrectly, and works well when jerked?","seatbelt","belt","tie","sash"},
{"What’s beautiful and natural, but gets prickly if it isn’t trimmed regularly?","lawn","park","tree","hair"},
{"All men have one, but it’s longer on some than others. The Pope never uses his, and a man gives it to his wife once they’re married.","last name","first name","middle name","nickname"},
{"I assist with erections. Sometimes, giant balls hang from me. I’m known as a big swinger. What am I?","crane","wrecking ball","giant arm","hook"},
{"You find me in a guy’s pants. I’m about six inches long, I have a head, and some women love to blow me. What am I?","twenty dollar bill","credit card","check","ID"},
{"When I go in, I can cause some pain. I’ll fill your holes when you ask me to. I also ask that you spit, and not swallow. What am I?","dentist","Dermatologists ","Endocrinologists ","Colon and Rectal Surgeons "},
{"I grow in a bed, first white then red, and the plumper I get, the better women like me. What am I?","strawberry.","raspberries"," blueberries"," blackcurrants"},
{"I’m the highlight of many dates. I’m especially responsive when you put your fingers deep inside me. What am I?","bowling ball","basketball","baseball","soccer"},
{"What’s made of rubber, handed out at some schools, and exists to prevent mistakes?","Erasers","pencils","chalk","paper"},
{"I’m at least six inches long. I love it wet and foamy when I get to do my job. What am I?","toothbrush.","comb","brush","sponge"},
{"Over 1,000 people went down on me. I wasn’t a maiden for long. Something really big and hard ripped me open. What am I?","titanic","train to busan","snake on a plane","fast and furious"},
{"It’s a fun thing to do and you devote a significant amount of energy to thinking about it, but you hate knowing that your parents are doing it. What is it?","facebook","twitter","instagram","youtube"},
{"What’s most useful when it’s long and hard?","education","patience","relationship","trust"},
{"What’s white, sticky, and better to spit than to swallow?","toothpaste","glue","mayonnaise","milk"},
{"A lot of people like these to be as long as possible, but short ones can be effective, and it’s definitely possible for them to be too long. What are they?","tweets","cooments","reply","post"},
{"Name a word that’s four letters long, ends in “u-n-t” and is used to refer to some women?","aunt","uncle","grandmother","grandfather"},
{"What does a woman have two of the a cow has four of?","legs","arms","foot","toe"},
{"What goes up, lets out a load, and then goes back down?","elevator","bus","plane","rocket"},
{"If you put three fingers into these holes, it's gonna be a shocker. What am I talking about?","power outlet","window","bowlingball holes","ears"},
{"Some people prefer being on top, others prefer being on the bottom, and it always involves a bed.","bunk bed","floor","bedroom","bedrock"},
{"What goes naked to keep you warm?","sheep","cow","chicken","fish"},
{"What does a gay horse eat?","haaaay","grass","leaves","fish"},
{"If there is H2O on the inside of a fire hydrant, what is on the outside? ","K9P","CuTe","SiLi","h2"},
{"What word starts with ''c'' and ends with ''t'' and is synonymous with pussy?","cat","chicken","crow","cow"},
{"what is tall when it's young and short when old?","candle","pole","building","statue"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third_quiz);
countLabel = (TextView)findViewById(R.id.countLabel);
questionLabel = (TextView)findViewById(R.id.questionLabel);
answerBtn1 = (Button)findViewById(R.id.answerBtn1);
answerBtn2 = (Button)findViewById(R.id.answerBtn2);
answerBtn3 = (Button)findViewById(R.id.answerBtn3);
answerBtn4 = (Button)findViewById(R.id.answerBtn4);
Typeface font3 = Typeface.createFromAsset(getAssets(), "GrinchedRegular.otf");
countLabel.setTypeface(font3);
questionLabel.setTypeface(font3);
answerBtn1.setTypeface(font3);
answerBtn2.setTypeface(font3);
answerBtn3.setTypeface(font3);
answerBtn4.setTypeface(font3);
//Receive from StartuActivitu
quizCategory = getIntent().getIntExtra("QUIZ_CATEGORY",0);
Log.v("CATEGORY_TAG", quizCategory + "");
// Create quizArray from quizData.
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Country
tmpArray.add(quizData[i][1]); // Right Answer
tmpArray.add(quizData[i][2]); // Choice1
tmpArray.add(quizData[i][3]); // Choice2
tmpArray.add(quizData[i][4]); // Choice3
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Q" + quizCount);
// Generate random number between 0 and 14 (quizArray's size - 1).
Random random = new Random();
int randomNum= 0;
if(quizCategory==0){
randomNum = random.nextInt(quizArray.size());
}
else if (quizCategory==1){
randomNum = random.nextInt(50 - 0) + 0 ;
}
else if (quizCategory==2){
randomNum= random.nextInt(100 - 50) + 50;
}
else {
randomNum= random.nextInt(150 - 100)+100;
}
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set question and right answer.
// Array format: {"Country", "Right Answer", "Choice1", "Choice2", "Choice3"}
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Country" from quiz and Shuffle choices.
quiz.remove(0);
Collections.shuffle(quiz);
// Set Choices.
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
answerBtn4.setText(quiz.get(3));
// Remove this quiz from quizArray.
quizArray.remove(randomNum);
}
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)) {
// Correct!
alertTitle = "Correct!";
rightAnswerCount++;
} else {
// Wrong...
alertTitle = "Wrong...";
}
// Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + rightAnswer);
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
// Show Result.
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}
Lastly let me add that i havent put the last details on index 100-150 our if fits realy index sorry if im stupid or sound stupid im fairly new ot this im really sorry.
Related
Test instances always classified in to the the same class
I have written a java program that build a J48 classifier using training set. Then I pass a test instance to the classifier to predict the unknown class. But each and every test instance classified in to first element of the class attribute. example : - if I declare element of class attributes, cls.add("positive"); cls.add("negative"); In this order, each instance classified in to first class element which is positive. If I declare class element in this order, cls.add("negative"); cls.add("positive"); each instance classified in to first class element which is negative. My training set shows more than 90% accuracy in weka explore. public static void main(String[] args) throws Exception { StringToWordVector filter = new StringToWordVector(); //training set BufferedReader reader; reader = new BufferedReader(new FileReader("D:/suicideTest.arff")); Instances train = new Instances(reader); train.setClassIndex(train.numAttributes() -1); filter.setInputFormat(train); train = Filter.useFilter(train, filter); reader.close(); J48 nb = new J48(); nb.buildClassifier(train); ArrayList cls = new ArrayList(2); cls.add("positive"); cls.add("negative"); Attribute clsAtt = new Attribute("class", cls); //ArrayList<String> tweet = new ArrayList(1); //String tweet = ""; //Attribute tweetAtt = new Attribute("tweet", tweet); ArrayList allAtt = new ArrayList(2); //allAtt.add(tweetAtt); allAtt.add(new Attribute("tweet", (FastVector) null)); allAtt.add(clsAtt); // Create an empty test set Instances testSet = new Instances("", allAtt, 1); // Set class index testSet.setClassIndex(testSet.numAttributes() - 1); String names= "Fox News Devotes a Whole Evening[']s Worth of Programming to Whining About CNNAgain (column by #justinbaragona)"; Instance inst = new DenseInstance(2); inst.setValue((Attribute)allAtt.get(0), names.toString()); testSet.add(inst); System.out.println(testSet.instance(0).toString()); double pred = nb.classifyInstance(testSet.instance(0)); filter.setInputFormat(testSet); testSet = Filter.useFilter(testSet, filter); String predictString = testSet.classAttribute().value((int) pred); System.out.println(predictString); } my training set look like #RELATION suicidalideation #ATTRIBUTE tweet string #ATTRIBUTE class {positive,negative} #DATA "is it weird to be tired of living. i just. don't want to exist for a while", positive "I don't want to exist", positive "i don't want to exist in this world without you", positive "I simply just don't want to exist anymore.", positive "I don't want to exist im fed up of all this shit", positive "I am deeply sad that i don't want to exist now", positive "It's feel like I don't want to exist to anybody life", positive "fuck me up i don't want to exist for myself", positive "I don't want to be alone, I don't want to be in my room, I don't want to exist", positive "I just kind of don't want to exist right now cause stress is just too much", positive "if i'm going to be a problem i don't want to exist", positive "If he leaves me I don't want to go on anymore..will jump to running train ..", positive "Im dead inside and I don't want to go on.", positive "I don't want to go on living in this world without you", positive "I hate my life and Don't want to go on further", positive "I dont want to go on living in this world without you", positive "Wance&Forall | Coming SoonnHow soon depends on you!nLIKE/FOLLOW Wance & Forall on " , negative "RT #ChampionsLeague: Zidane: Toughest opponent? Scholes. The complete midfielder; undoubtedly the greatest midfielder of his generation.[...]" , negative "You are excited to participate in activities with people who m... " , negative "RT #pussypun: rub ur ass against his dick by accident on purpose" , negative "RT #NiallOfficial: Have a great 4th of July , America" , negative "RT #thedrewpowell: Happy Birthday America! #FourthOfJuly" , negative "RT #virtuaIg: she a child sir " , negative "Happy 4th of July Fillies! Good day to play some golf. Coach played 9. How bout you? " , negative "#TheEFCForum Fair enough. We will see. But I'm doubting I'm going to be wrong on this to be honest, if I am fair enough." , negative "RT #_EVANGELO: We are aware we weren't free on this date. Please shut the entire fuck up and EAT. Gaddamn! Every damn holiday y'all got som[...]" , negative "Langley's Abbey Fortin going to bat for Canada #Langley #bhivecan" , negative "Daily Organic Multivitamins for Kids GLUTEN FREE - SUGAR FREE - VEGAN - KOSHER - HALAL VITAMIN SUPPLEMENTS Nutra Pharmnmultivitamin has 45" , negative "RT #skinupgg: ST SSG 08 DRAGONFIRE GIVEAWAY OH MY GOD nnIT'S SO LIT nTO ENTERnn[?] RETWEET & FOLLOWn[?] " , negative "RT #DerekCressman: Happy July 4th. Let's Declare American Independence from Russian interference in our sovereignty" , negative "RT #wordstionary: Never let your past dictate your future. It's never too late to become better." , negative "RT #Jon_Wienke: Stopped to clean his sign. Nothing but respect for my president. " , negative "#Ayindeemu Please help my friend win the #isokenmovie #IsokenMegaGiveaway contest by liking the tweet above Please!n #_idarahh" , negative "RT #politicques: What to The Slave is 4th of July? -- 1841 Speech by Frederick Douglass -- Courtesy of The Freeman Institute... " , negative "idk why that bothers me" , negative "RT #JPY_Kurdish: Stoke-on-Trent, England: [?] pedophile hunter group catches a Muslim man who wants to meet a 13-year-old girl for sex at Cen[...]" , negative "#Danny_Draws Hah, that's very Portland. I wonder if it affects water pressure. :)" , negative "RT #CSGORoll: AK-47 | Case Hardened FTnn- RTn- Follown- Enable notifications on CSGORolln- Play " , negative "Nobody can go back... Maria Robinson #quote #quotes #inspiration #findyourhappily " , negative "RT #ManuBlinkVIP: Rosé talking about IU again! You're doing great sweetie, keep mentioning that, this collab must happen!" , negative "need to be as lit as the fireworks tonight" , negative "#RyderDanielz #davey_sap ...I think he would be a great opponent for me at 'Chantz Of A Lifetime' for my titles." , negative "RT #RealNiggy_: well if you move i could see all my options " , negative "#Komangsrie21 polback donv" , negative "RT #PeadaPipper: Easy Breezy Beautiful. " , negative
k.next statement [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 5 years ago. Improve this question 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."); } } } } }
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.
Android find repeat values in ArrayList [duplicate]
This question already has answers here: How to count the number of occurrences of an element in a List (25 answers) Closed 6 years ago. Got an ArrayList like that. Wanna find how many values are repeated: Example: person:4 times , girl:4 times public ArrayList<String> new_contains_all= new ArrayList<>(); ... [[laying, beautiful, brushing, group, young, head, bed, close, couple, female, teeth, white, indoor, pair, holding, sunglasses, stuffed, wearing, posing, dress, person, hair, standing, looking, girl, red, playing, made, top, woman, lady, hat, clothing, goggles, people], [person, hair, young, shirt, looking, phone, girl, white, glasses, food, sunglasses, wearing, woman, hat], [blue, beautiful, person, cake, standing, young, shirt, black, female, board, girl, white, photo, holding, ready, wearing, top, posing, woman, lady, smiling, clothing, dress, suitcase], [street, clock, light, stop, sign, red, text, sitting, man, photo, traffic], [blue, person, young, looking, phone, sitting, female, girl, photo, computer, using, red, laptop, holding, glasses, food, sunglasses, wearing, top, woman, lady, hat]] Notify that the Array have 5 elements inside. Already tried this, that should be working for simple ArrayList but with more than 1 string per element its creepy, i know the solution must implement another bucle inside key, but so tired for today :/ maybe someone blinks my mind :P List<String> l = new_contains_all; Set<String> s = new HashSet<String>(l); for (String key : s) { int count = Collections.frequency(l, key); if (count > 1) System.out.println("Found '" + key + "' " + count + " times."+"key: "+key.toString()+"l: "+l.toString()); }
You almost solved your problem, but there is one subtle bug in your code: Set<String> s = new HashSet<String>(l); The core property of a Set is: it doesn't allow for duplicates. Thus this one call simply removes all duplicates from that input list l. Thus: all frequencies will be one. So, instead, you can do: for (String singleWord: new_contains_all) { count = Collections.frequency(new_contains_all, singleWord); ...
How do I print a random word from a string array? Java
I have to make the three arrays in my code (shown below) to print randomly. So for "Today:" and "Tomorrow" print a random good or bad comment. For your lucky and not so lucky days, print a random date and a random good comment for the lucky day and random bad comment for the not so lucky day. I don't know how to pick randomly from string arrays. I have this due tomorrow and I just started coding a few months ago so im not sure how I would go about doing this. Today: You will meet an old friend! Tomorrow: Trust your intuition. The universe is guiding your life. Your lucky day for 2016 is November 4: You will win the jackpot. Your not so lucky day for 2016 is January 24: Power failure day This is my code: String Month[]={"January","Febuary","March","April","May","June","July","August","September","October","November","December"}; String goodcomment[]={"None of the secrets of success will work unless you do","Today is a lucky day for those who remain cheerful and optimistic","You were born with the skill to communicate with people easily","The first step to better times is to imagine them","Trust your intuition. The Universe is your guiding light","It doesnt matter. Who is without a flaw?","Your happiness is interwined with your outlook on life","The secret of getting ahead is getting started", "Failure will never overtake you if my determination to succeed is strong enough.","What you do today can improve all your tomorrows.","In order to succeed, you must first believe that you can.","Always do your best. What you plant now, you will harvest later."}; String badcomment[]={"Power failure today","You'll miss the bus","Too many things to do and not enough time","University entranced denied","You'll lose your phone","You'll miss your date","You'll forget someone close to you's birthday", "Today is a disastrous day. If you can’t beat ’em, join ’em","You will meet someone next week that will bring negativity into your life","Don't step on a crack","You will wake up sad tomorrow","Your car will break down"};
You can use the Random class for this. The method nextInt(int bount) will return a random integer from 0 to bound-1. So to randomly select a string from an array, you can do: Random random = new Random(); int randomIdx = random.nextInt(goodComment.length); System.out.println(goodComment[randomIdx]);
Solution will be obtaining selecting a random number from 0 or 1 to select randomly from good or bad comment (i.e. 0 – good comment and 1 – bad comment). Then selecting a comment randomly from the selected array by obtaining a random number from 0 to (length of the selected array – 1) in order to indicate the index of the printing comment. You can use the approach suggested by tixopi to generate the random number. private String goodcomment[] = { "None of the secrets of success will work unless you do", "Today is a lucky day for those who remain cheerful and optimistic"}; private String badcomment[] = { "Power failure today", "You'll miss the bus", "Too many things to do and not enough time", "University entranced denied", "You'll lose your phone", "You'll miss your date"}; private Random indexGenerator = new Random(); public void printCommentWithPrefix(String prefix) { System.out.println(prefix + " : " + selectRandomGoodOrBadComment()); } private String selectRandomGoodOrBadComment() { String randomGoodOrBadComment; if (selectEitherGoodOrBad() == 0) { randomGoodOrBadComment = selectAComment(goodcomment); } else { randomGoodOrBadComment = selectAComment(badcomment); } return randomGoodOrBadComment; } private int selectEitherGoodOrBad() { int goodOrBadIndicator = indexGenerator.nextInt(2); return goodOrBadIndicator; } private String selectAComment(String[] comment) { int indexOfSelectedComment = indexGenerator.nextInt(comment.length); String selectedComment = comment[indexOfSelectedComment]; return selectedComment; }
JOptionPane variable might not have been initialized
I'm sorry the code is so long, I just need to know what I'm missing to initialize all my decisions. The compiler is complaining about my variable not being initialized. Thank you. import javax.swing.JOptionPane; public class SemesterProject { public static void main(String[] args) { String SemesterProject = "Hello and welcome to Juans adventure story! Your choices throughout this story will bring your doom or your salvation!\n"+ "No one has been able to complete this story and lived to tell the tale, but maybe you will be the first one!.\n"+ "Our story begins in the small town of Badow. Many people in the town spread rumors of brave adventurers that\n"+ "go on the quest to solve the mysterious riddles of the abandond castle at the top of the hill.\n"+ "No one really knows who or what lies at the heart of the castle. Legend says that monsters guards the\n"+ "the many riches once owned by the family that died there, so many years ago.\n"+ "The Castle is full of dizzing turns and hidden corridors and dangerous monsters. Many adventureres \n"+ "have gone insane because of how they lose their way or go get stuck. It is the hardes quest known to man.\n"+ "The quest for you is to go to the castle, solve the riddles and claim the riches.\n"+ "The world will little note, nor long remember what we say here, but it can never forget what they did here.\n"+ "Be careful. Watch your back and always mark your trail because you never know what you will find next.\n"+ "If for some crazy reason you end up successful in this task, you will not only get the riches in the castle but\n"+ "you will also be crowned the king of the town of Badow. If you die, you lose.\n"+ "The last thing you have to do is input some of your personal information so that we keep you in our records.\n"; JOptionPane.showMessageDialog(null,SemesterProject); String name = JOptionPane.showInputDialog(null,"Please give us your first name."); String age = JOptionPane.showInputDialog(null,"Please give us your age."); String weight = JOptionPane.showInputDialog(null,"Please give us your weight."); String haircolor = JOptionPane.showInputDialog(null,"Please give us your hair color."); String GPA = JOptionPane.showInputDialog(null,"Please give us your GPA."); String favoritecolor = JOptionPane.showInputDialog(null,"Please give us your favorite color."); String decision1,decision2,decision3,decision4,decision5,decision6; decision1 = JOptionPane.showInputDialog("Brave adventurer, welcome to the entrance of the abandoned castle of town Badow. At this moment\n"+ "You have a choice right now to give up and take a walk of shame back to the village, and to safety\n"+ "Or you can decide to go in and test your unique set of skills on the various challenges of the adventure\n"+ "ahead of you. Enter the number of your choice.You can either 1. Enter the castle 2. Stay behind."); if (decision1.equals("1")) { decision2 = JOptionPane.showInputDialog ("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+ "or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+ "to keep track of were you are. 1. Into the room 2. Down the hall."); } else { JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+ "lost your chance at getting the riches that lie deep in the castle. You lose."); } if (decision2.equals("1")) { decision3 = JOptionPane.showInputDialog ("You step into the room and find some medication and a lantern with some oil.\n"+ "you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+ "a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor."); } else { JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+ "makes you crazy."); } if (decision3.equals("1")) { decision4 = JOptionPane.showInputDialog ("You are back in the hall slowly hearing the echoing sound of your footsteps\n"+ "you head downstairs into what seems to be another hallway but this one full of barred rooms, kind of like a dungeon. There is\n"+ "a skeleton body on the ground which seems to be of another failure by an adventurer in the castle. You reach the end of the hall\n"+ "and there is two ways to go left or right. 1. Left 2. Right."); } else { JOptionPane.showMessageDialog(null,"You squeeze through the trapdoor and fall down to the ground where you find youself lost and disoriented\n"+ "You dont know where you are and start to panic, you start becoming insane and die."); } if (decision4.equals("1")) { decision5 = JOptionPane.showInputDialog ("You go left and hear a door open behind you, you panic and start to run\n"+ "you run intro different halls to try and escape but you trip. You just remembered that you have a sword with you and can now\n"+ "choose what to do 1. Take out sword and fight enemy 2. Get up and keep running."); } else { JOptionPane.showInputDialog(null,"You go right and get locked in behind you. You realize that there isnt anwhere to go\n"+ "and get lost in the darkest part of the castle and die alone."); } if (decision5.equals("1")) { decision6 = JOptionPane.showInputDialog ("You were able to fight of the armored enemy. But something tells you that that isnt the last of them. You continue on down the\n"+"hall and see from the distance to what seems to be your first prize. It cant be that easy."); } } }
Define the decision variables as null. Instead of: String decision1,decision2,decision3,decision4,decision5,decision6; Define the variables as: String decision1 = null; String decision2 = null; String decision3 = null; String decision4 = null; String decision5 = null; String decision6 = null;
decision2 is only being set if decision1 is equal to 1. I think you want to put the if statements for the other decisions inside of each other like below: if (decision1.equals("1")) { decision2 = JOptionPane.showInputDialog ("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+ "or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+ "to keep track of were you are. 1. Into the room 2. Down the hall."); if (decision2.equals("1")) { decision3 = JOptionPane.showInputDialog ("You step into the room and find some medication and a lantern with some oil.\n"+ "you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+ "a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor."); } else { JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+ "makes you crazy."); } } else { JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+ "lost your chance at getting the riches that lie deep in the castle. You lose."); }
You must initialize your String variables (decision1, decision2,...) as: String decision1 = null, decision2 = null, decision3 = null, decision4 = null, decision5 = null, decision6 = null; Note that you don't get a compile error for decision1 because in the line decision1 = JOptionPane.showInputDialog(...); it is being initialized. Also, your program's logic is bad. If decision1 is not 1, then you will just show a message, but the program will continue to check the next condition: if (decision2.equals("1")) where you will get a NullPointerException because you are comparing null with 1.
JOptionPane variable might not have been initialized So keep in mind one thing that whenever you get such kind of error messages try to see that your variables are properly declared. See when you try to use int variable it can give you error message if that variable is used in some computation. So try to initialize the variables like: int a=0; You can do the same thing with string variables also like: String a=null; Returning to answer In your code you have just declared the variables , but the fact is that you have to actually initialize them. Replace String decision1,decision2,decision3,decision4,decision5,decision6; By String decision1=null,decision2=null,decision3=null,decision4=null,decision5=null,decision6=null;