繁体   English   中英

我不知道如何使用带有 if 语句字符串比较的 while 循环

[英]i can't figure out how to use a while loop with an if statement string comparison

我正在为学校开发这款基于文本的冒险游戏,如果玩家在游戏中没有选择选项 1 或选项 2,我会陷入循环状态,因此系统将打印“请选择一个选项”但是我不知道该怎么做。

我尝试使用 for-loops、do-loops,使用 || or 语句而不是使用 && 语句,而只是使用普通的 if 语句,但它们没有奏效。

import java.util.Scanner;

public class Input
{

public static void main(String[] args)
{
    Scanner scanny = new Scanner(System.in); // scanner name is scanny fyi

    System.out.print("Press Enter to begin game"); //first message!

    String EnterPress = scanny.nextLine(); //varible for when you press 
                                                                     enter

System.out.println("\nyou begin as a man named Mason Grey, you are 30 
years old, you went to college to learn how to become a detective, your 
parents are paying for your house, you were just fired from your job at 
the Police Station 1 month ago, and you have a girlfriend named Beth.");

    pause(7);

    System.out.println("\nyou arouse inside of a moving taxi");

    pause(1);

    System.out.println("\nwhat do you do?");

    pause(1.2);

    System.out.println("\nOption 1: Check your cellphone in your back 
pocket");//Option 1

    pause(1.2);

    System.out.println("\nOption 2: Ask where you are");//Option 2

    String ChoiceFirst = scanny.nextLine(); // First choice string for 
option 1 and 2

    while ((!(ChoiceFirst.equalsIgnoreCase ("Option 1"))) && (! 
 (ChoiceFirst.equalsIgnoreCase ("Option 2"))))

    {
        System.out.println("\nPick an Option Please");
    }

    if (ChoiceFirst.equalsIgnoreCase ("Option 1") ) // if the player types 
in "Option 1" then it will print the script                   |CellPhone|
    {
        System.out.println("\nYou unlock your phone with your passcode, 
the bright blue LED light hurts your eyes as you squint in the black 
leather backseat of the cab. You open your text messages with a tap and 
see 23 unread messages from your girlfriend, Beth.You groan and tap on the 
messages,\n and see the last message: \n“Mason, could you come to the 
house please? I need help with the toilet again.”");

        //This is the beginning of the A1 tree or the first option tree

        pause(6);

        System.out.println("\nwhat do you do now?"); //question asked for 
Option 1 tree

        pause(1.2);
 public static void pause(double secondsToPause) // pause function
{
    try
    {
        // type casting the resurt of the double times a long back into a 
long
        Thread.sleep((long)(1000*secondsToPause));
    }
    catch(InterruptedException ex)
    {
        Thread.currentThread().interrupt();
    }
  }
}

如果他们不输入选项 1 或选项 2,我只希望游戏到 output “请选择一个选项”

完整代码:

import java.util.Scanner;

public class Input
{

public static void main(String[] args)
{
    Scanner scanny = new Scanner(System.in); // scanner name is scanny fyi

    System.out.print("Press Enter to begin game"); //first message!

    String EnterPress = scanny.nextLine(); //varible for when you press enter

    System.out.println(" \n\n");
    pause(.3);
    System.out.println("        ./osyhhhhhhhhyso/-                                                                                                                                                                                .yyyyyyy.");
    pause(.3);
    System.out.println("     `/yhhhhhhhhhhhhhhhhhhy/`                                                                                                                                                                             .hhhhhhh-");
    pause(.3);
    System.out.println("    .yhhhhhhhhhyyyyhhhhhhhhhy.                                                                                                                                                                            .hhhhhhh-");
    pause(.3);
    System.out.println("   .hhhhhhhh+-``````./yhhhhhhh.                                                                                                                                                                           .hhhhhhh-");
    pause(.3);
    System.out.println("   yhhhhhhy.          `shhhhhhs                                                                                                                                                                           .hhhhhhh-");
    pause(.3);
    System.out.println("  :hhhhhhh-            .hhhhhhh.                                                                                                                                                                          .hhhhhhh-");
    pause(.3);
    System.out.println("  ohhhhhhh              yhhhhhh/                                                                                                                                                                          .hhhhhhh-");
    pause(.3);
    System.out.println("  yhhhhhhy              shhhhhh+                      ```             ``.```                                                 ``.``                      ``..``                       ``..``               .hhhhhhh-               ```.``");
    pause(.3);
    System.out.println("  hhhhhhhs              shhhhhh+       -sssssss   `:osyyy`       .:+syyyyyyyys+-`       +ssssss/         `sssssss-      `:+syyyyyyyo/.             `:+syyyyyyyys+:.             .:+syyyyyyyys+-`          .hhhhhhh-          `-+syyyyyyyys+:`");
    pause(.3);
    System.out.println(" `hhhhhhhs              `......`       -hhhhhhh``+yhhhhhh.     .oyhhhhhhhhhhhhhhy:      :hhhhhhy         -hhhhhhh`    `+yhhhhhhhhhhhhyo`         `+yhhhhhhhhhhhhhhy+`         .ohhhhhhhhhhhhhhhy:         .hhhhhhh-        `/yhhhhhhhhhhhhhhy+`");
    pause(.3);
    System.out.println(" `hhhhhhhs                             -hhhhhhh:yhhhhhhhh.    -yhhhhhhysooshhhhhhh/      yhhhhhh-        ohhhhhh+    `shhhhhhysooshhhhhy.       `shhhhhhysoosyhhhhhhs`       :hhhhhhhysosyhhhhhhh+        .hhhhhhh-       `shhhhhhysoosyhhhhhho");
    pause(.3);
    System.out.println(" `hhhhhhhs                             -hhhhhhhhhhyssossy`   `yhhhhhh/`   `.yhhhhhh.     /hhhhhho       `hhhhhhh.    +hhhhhh/`   `-yhhhhy`      ohhhhhho.    `+hhhhhh:      .hhhhhhh:`   `:hhhhhhh-       .hhhhhhh-       ohhhhhho.    `ohhhhhh/");
    pause(.3);
    System.out.println(" `hhhhhhhs                             -hhhhhhhho-`    ``    /hhhhhhs       :hhhhhh+     `yhhhhhh`      :hhhhhho     yhhhhhy       .hhhhh:     .hhhhhhh`      `hhhhhhs      ohhhhhh+       ohhhhhho       .hhhhhhh-      .hhhhhhh`      `hhhhhhy");
    pause(.3);
    System.out.println(" `hhhhhhhs                             -hhhhhhh:             shhhhhh/       .hhhhhhy      /hhhhhh:      ohhhhhh.     yhhhhhy`       +yso/.     :hhhhhhy        shhhhhh      yhhhhhh-       /hhhhhhh       .hhhhhhh-      /hhhhhhs        yhhhhhh.");
    pause(.3);
    System.out.println(" `hhhhhhhs       `++++++++++++++       -hhhhhhh`             hhhhhhh:       `hhhhhhh`     `hhhhhhs     `hhhhhhs      +hhhhhhy:`     ``         +hhhhhhs        shhhhhh      ///++++.       :hhhhhhh       .hhhhhhh-      ohhhhhho        shhhhhh:");
    pause(.3);
    System.out.println(" `hhhhhhhs       .hhhhhhhhhhhhhh       -hhhhhhh`             hhhhhhh:       `hhhhhhh`      +hhhhhh`    :hhhhhh-      `ohhhhhhhs:`              ohhhhhhs        ://////                    `/hhhhhhh       .hhhhhhh-      ohhhhhho        shhhhhh/");
    pause(.3);
    System.out.println(" `hhhhhhhs       .hhhhhhhhhhhhhh       -hhhhhhh`             hhhhhhhsoooooooohhhhhhh.      `hhhhhh/    shhhhhy        `/yhhhhhhhy/`            ohhhhhhs                              `.:+syhhhhhhhh       .hhhhhhh-      ohhhhhhyoooooooohhhhhhh/");
    pause(.3);
    System.out.println(" `hhhhhhhs        ......-hhhhhhh       -hhhhhhh`             hhhhhhhhhhhhhhhhhhhhhhh.       ohhhhhs   `hhhhhh/          .+yhhhhhhhy+.          ohhhhhhs                           .:oyhhhhhhhhhhhhh       .hhhhhhh-      ohhhhhhhhhhhhhhhhhhhhhh/");
    pause(.3);
    System.out.println(" `hhhhhhhs              `hhhhhhh       -hhhhhhh`             hhhhhhh+:::::::::::::::`       .hhhhhh.  /hhhhhy`            `/shhhhhhhy+.        ohhhhhhs                        `:ohhhhhhyo:/hhhhhhh       .hhhhhhh-      ohhhhhhs:::::::::::::::.");
    pause(.3);
    System.out.println(" `hhhhhhhs              `hhhhhhh       -hhhhhhh`             hhhhhhh:                        ohhhhh+  shhhhh+               `-shhhhhhhh/`      ohhhhhhs                       :yhhhhhho-`  :hhhhhhh       .hhhhhhh-      ohhhhhho");
    pause(.3);
    System.out.println("  hhhhhhhs              .hhhhhhh       -hhhhhhh`             hhhhhhh:                        -hhhhhy `hhhhhh`                  .+yhhhhhhs`     ohhhhhhs        .......       +hhhhhho.     :hhhhhhh       .hhhhhhh-      ohhhhhho");
    pause(.3);
    System.out.println("  yhhhhhhy              -hhhhhhh       -hhhhhhh`             hhhhhhh:       `+++++++`         shhhhh-/hhhhho                     .+hhhhhhs     ohhhhhhs        shhhhhh      /hhhhhho       :hhhhhhh       .hhhhhhh-      ohhhhhho        /++++++-");
    pause(.3);
    System.out.println("  +hhhhhhh.             +hhhhhhh       -hhhhhhh`             yhhhhhh:       `hhhhhhh`         -hhhhh+shhhhh.        `.:/os:        /hhhhhh:    +hhhhhhs        shhhhhh     `hhhhhhh-       :hhhhhhh       .hhhhhhh-      +hhhhhho        shhhhhh:");
    pause(.3);
    System.out.println("  .hhhhhhho            -hhhhhhhh       -hhhhhhh`             ohhhhhh/       .hhhhhhy           shhhhhhhhhhs         ohhhhhy`        hhhhhh/    -hhhhhhy        yhhhhhy     .hhhhhhh-       /hhhhhhh       .hhhhhhh-      -hhhhhhs        yhhhhhh-");
    pause(.3);
    System.out.println("   /hhhhhhho.        `:yhhhhhhhh       -hhhhhhh`             -hhhhhhy`      /hhhhhh+           :hhhhhhhhhh-         :hhhhhh+`      `hhhhhh:    `yhhhhhh-      .hhhhhh+     .hhhhhhhs`    .+hhhhhhhh`      .hhhhhhh-      `yhhhhhh-      .hhhhhhy");
    pause(.3);
    System.out.println("    ohhhhhhhhs+/:://oyhhhyohhhhh       -hhhhhhh`              ohhhhhhs:.``-+hhhhhhy`            yhhhhhhhhs           +hhhhhhs:.``.:yhhhhhs      :hhhhhhh/.``.:yhhhhhh.      shhhhhhhyo++shhyhhhhhhh`      .hhhhhhh-       :hhhhhhy/.``.:yhhhhhh:");
    pause(.3);
    System.out.println("     :yhhhhhhhhhhhhhhhhhs.:hhhhh       -hhhhhhh`              `ohhhhhhhhhhhhhhhhhy.             /hhhhhhhh:            /hhhhhhhhhhhhhhhhhs`       /hhhhhhhhhhhhhhhhhh:       `shhhhhhhhhhhhs`shhhhhh-      .hhhhhhh-        /hhhhhhhhhhhhhhhhhh:");
    pause(.3);
    System.out.println("      `/shhhhhhhhhhhhhy:  `hhhhh       -hhhhhhh`                -oyhhhhhhhhhhhhy/`              `hhhhhhhy              .+yhhhhhhhhhhhys:          .oyhhhhhhhhhhhhy+.         `/yhhhhhhhhy/` /hhhhhh/      .hhhhhhh-         .+yhhhhhhhhhhhhy+.");
    pause(.3);
    System.out.println("         `-/+ooosoo+:.     :::::       `:::::::                   `-:/+oooo+/:.                  +hhhhhh/                 .:/+ooo++:-`              `-:/+oooo+/:-`             `-/+oo+/-`   `::::::.      `:::::::`            .:/+oooo+/:-`");
    pause(.3);
    System.out.println("                                                                                                 +hhhhhh`");
    pause(.3);
    System.out.println("                                                                                          -://++shhhhhh:");
    pause(.3);
    System.out.println("                                                                                          ohhhhhhhhhhy:");
    pause(.3);
    System.out.println("                                                                                          ohhhhhhhyo:");                                                                                                                                                
    pause(.3);
    System.out.println("                                                                                          -//::-.`");            

    pause(5);

    System.out.println("\nyou begin as a man named Mason Grey, you are 30 years old, you went to college to learn how to become a detective, your parents are paying for your house, you were just fired from your job at the Police Station 1 month ago, and you have a girlfriend named Beth.");

    pause(7);

    System.out.println("\nyou arouse inside of a moving taxi");

    pause(1);

    System.out.println("\nwhat do you do?");

    pause(1.2);

    System.out.println("\nOption 1: Check your cellphone in your back pocket");//Option 1

    pause(1.2);

    System.out.println("\nOption 2: Ask where you are");//Option 2

    String ChoiceFirst = scanny.nextLine(); // First choice string for option 1 and 2

    while ((!(ChoiceFirst.equalsIgnoreCase ("Option 1"))) && (!(ChoiceFirst.equalsIgnoreCase ("Option 2"))))

    {
        System.out.println("\nPick an Option Please");
    }

    if (ChoiceFirst.equalsIgnoreCase ("Option 1") ) // if the player types in "Option 1" then it will print the script                   |CellPhone|
    {
        System.out.println("\nYou unlock your phone with your passcode, the bright blue LED light hurts your eyes as you squint in the black leather backseat of the cab. You open your text messages with a tap and see 23 unread messages from your girlfriend, Beth.You groan and tap on the messages,\n and see the last message: \n“Mason, could you come to the house please? I need help with the toilet again.”");

        //This is the beginning of the A1 tree or the first option tree

        pause(6);

        System.out.println("\nwhat do you do now?"); //question asked for Option 1 tree

        pause(1.2);

        System.out.println("\nOption 1:Text your girlfriend beth that you might be coming home late");//first selectable option for the Option 1 tree

        System.out.println("\nOption 2: Text your girlfriend if she wants chinese food");//second selectable option for the Option 1 tree

        System.out.println("\n");//indentation from the selectable options and the selected option for the Option 1 tree

        String ChoiceHome = scanny.nextLine();//input for the player for the first option for the Option 1 tree

        if (ChoiceHome.equalsIgnoreCase ("Option 1") ) //if you pick Option one it will print the script for the Option 1 tree           |HomeStatement|
        {
            System.out.println("\nYou text your girlfriend that you might be coming home late. You scroll up through the long list of messages she sent you about the toilet. You feel the cab car stop and look out the wet cab window to see that you’re home. You step outside of the cab and walk up to your house.\t When you take out your keys to open the door you see that it's open. You open the door and only 2 lights in the house are on. You walk around the living room and see a file on top of the small wooden table labeled GreyScale.");

            pause(5);

            System.out.println("What do you do now?");

            System.out.println("\nOption 1:Text you gf if she came home or not");

            System.out.println("\nOption 2: investigate the living room");

            System.out.println("");//indentation from the selectable options and the selected option for the Option 1 tree

            String ChoiceGf = scanny.nextLine();//input for the player for the first option (GF option)

            if (ChoiceGf.equalsIgnoreCase ("Option 1") )//girlfriend script
            {
                System.out.println("\nWith all of your strength and utmost quietness you pull your phone out of your back pocket and quickly text your girlfriend: Beth, did you come by the hou-  but you franticly turn off your phone as to hear a loud CRASH! outside of the apartment");

                pause(5);

                System.out.println("\nWhat do you do now?");

                pause(1.2);

                System.out.println("\nOption 1:Investigate the loud noise");

                System.out.println("\nOption 2:Run upstairs and GET YOUR GUN");

                System.out.println("");//indentation from the selectable options and the selected option for the Option 1 tree

                String ChoiceNoise = scanny.nextLine();//user input for the first option (Loud noise option)

                if (ChoiceNoise.equalsIgnoreCase ("Option 1") )//Loud noise option description
                {
                    System.out.println("\nYou stop and put down the file and walk through the kitchen and go out to the balcony, you look around in the dark rainy lime light street and you see a dumpster with a giant dent on the lid. You climb down the fire escape ladder on your balcony and walk to the other side of the alleyway towards the dumpster, completely drenched, you lean forward and find a small soaked sticky note with mushed pen marks,\n since it it isn't even legible, you don't bother with trying to decript it, you look to your left and squint through the loud stormy rain and see a cab...the cab driver! You look closely and see his silouhette juxtaposed by the bright flourescent yellow light down the street, your spine crawls .It almost looks as if he is staring directly at you, or behind you? \"Hello?\" you yell through the pouring rain, the cab driver \nrolls away and dissapears still staring down the street. ");

                    pause(5);

                    System.out.println("\nWhat do you do now?");

                    System.out.println("\nOption 1: Walk back inside with the sticky note");

                    System.out.println("\nOption 2: Go around the corner of the alleyway to see where the cab driver went");

                    String ChoiceSticky = scanny.nextLine(); // user input for sticky note option

                    if (ChoiceSticky.equalsIgnoreCase ("Option 1") )
                    {
                        System.out.println("\nYou pick up the wet sticky note with two fingers, careful not to get your fingers wet. You put the note into your pocket and look around to see if anybody is still here, just as you are about to leave the rainy alleyway, you feel a squish on your boots, and see that you have stepped on a dead bird? The questions in your head are piling up faster than you can comprehend:\n\"What is going on?\" \"Why is there a dead bird?\" \"Why am i still standing in this rain?\" you think to yourself, and you decide to leave the bird and walk back inside with the note, you close the door to keep the rain out, and walk into your room. You sit down in your chair and turn on the light next to your desk. You place the note on the table and try your hardest to understand what is even on the note.");

                        pause (5);

                        System.out.println("\nWhat do you do now?");





                    }

                    else if (ChoiceSticky.equalsIgnoreCase ("Option 2") )
                    {
                        System.out.println("\nYou run forward through the rain and turn look both ways, but the cab driver is already gone");
                    }
                }
                else if (ChoiceNoise.equalsIgnoreCase ("Option 2") )//Gun option
                {
                    System.out.println("\nYou immedietly wher remember your handgun is and you dash towards the stairs to your bedroom to get it from your cabinet next to your bed. As your about to open the cabinet you stop dead in your tracks and look out your window, to see that the dumpster under the window is completely dented and you make out a small yellow object in the center of the dent. You open the window as fast as you can and look outside to your left as your hair gets drenched in the salty rain. You see only one thing in the center of the end of the dark, narrow, alleyway,the cab driver.\t You see his dark, faceless figure staring at you with a daunting gaze, you snap out of the fearful trance and yell at the cab driver though the loud shattering rain: \nHEY! you yell, \nthe cab driver turns away and drives off into the dark, wet city lights.");
                }
            }
            else if (ChoiceGf.equalsIgnoreCase ("Option 2") ) //living 
room script` 
            {
                System.out.println("\nYou wipe your boots off on the 
carpet and walk as slow as you are physically able, staring intently at 
your open closet door. You feel as if you are literally crawling at the 
slowest speed ever to avoid your feet making any sound, as you peek into 
the wooden closet door, your eyes widen to see tht the basement door is 
wide open.");
            }
        }

        else if (ChoiceHome.equalsIgnoreCase ("Option 2") ) //Text GF 
chinese food script
        {
            System.out.println("\nYou text your girlfriend on your 
cellphone: \"Coming home do you want chinese food?\"\n slide your phone 
into your pocket and not even 2 seconds later, you feel a buzz. Confused, 
you take out your cellphone and turn on the phone, only to see she has 
messaged you back. You unlock your phone again, open your messages with a 
tap, and read the message: \n\"No im okay, ty though\"\n you're almost 
taken aback by her 
bizarre act of kindness, she usually hates talking to you and never says 
thank you at all, \"Somethings off\" you think to yourself " );
        }
    }

    else if (ChoiceFirst.equalsIgnoreCase ("Option 2") ) // if you pick 
Option 2 then it print the script for the Option 1 tree       |CabDriver|
    {                                                                                                                                                   
        System.out.println("\nYou ask the cab driver where you are, and 
he only responds with: You told me you wanted to head to queens, so thats 
where we're going. he says. You think for a moment, and realize that you 
have never even been to queens. You don't question the cab driver, but 
you definetly wonder if you are safe or not.");
    }
}

public static void pause(double secondsToPause) // pause function
{
    try
    {
        // type casting the resurt of the double times a long back into a 
long
        Thread.sleep((long)(1000*secondsToPause));
    }
    catch(InterruptedException ex)
    {
        Thread.currentThread().interrupt();
    }
  }
}

不要让用户实际输入: Option 1 玩这个游戏已经做太多工作了。 相反,允许用户为“选项 1”输入数字1 这意味着您需要重建您的菜单,并且该菜单应包含在您的while循环中:

String ls = System.lineSeparator();
String choiceFirst  = "";

while (choiceFirst .equals("")) {
    System.out.println("What do you do?" + ls);
    System.out.println("Options:" + ls + "========");
    System.out.println("1) Check your cellphone in your back pocket.");
    System.out.println("2) Ask where you are.");
    System.out.println("3) Bail out of the Cab without paying!");
    System.out.print("--> ");
    choiceFirst = scanny.nextLine();
    // Make sure the entry is either "1" or "2". If not then loop
    if (!choiceFirst.matches("[1-3]")) {
        System.err.println("Invalid entry (options 1 to 3 only)" + ls);
        choiceFirst = "";
    }
} // End of while loop

if (choiceFirst.equals("3")) {
    System.out.println("You bail out of the Cab to avoid paying and break "
            + "your neck, you die instantly!" + ls + "On a good day when "
            + "you've eaten your Cherrios you would have successfull made" + ls 
            + "this jump but then you would have most likely died sitting "
            + "on the toilet dumping " + ls + "the stuff. Thanks for playing"
            + "...Bye Bye");
    System.exit(0);
}

嗯……是这样的。 将所有提示放入不同的while循环中,并在每个循环中验证用户的输入。 如果输入无效,则通知用户并允许再次输入或选择退出或退出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM