我的阵列没有上升

时间:2015-01-01 21:04:13

标签: java arrays

我正在开发基于文本的冒险游戏。 (这根本不是OOP)问题出现在我的循环中的第二个if语句中,它没有向我的数组位置添加1 []它保持打印位置[0]然后结束时为1。不太确定这里发生了什么。

package com.PenguinGaming;

import java.util.Scanner;

public class Game{


    /*
     * Command list:
     * - investigate (advanced description)
     * - go north
     * - go south
     * - go west
     * - go east
     * - pick up
     * - eat
     * - drink from
     * - drink object
     * - climb up/down
     * - burn
     * - use object
     * - attack
     * - defend
     * - description (basic description)
     * - read
     * - life
     * - help (brings up command list)
     */

    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);

        int life = 25;

        boolean running = true;

        String input = null;

        String[] locations = new String[3];
        locations[0] = "Location: Canyon\nDescription: You stand alone over looking a large caynon, \nwater crashing" +
        " into the forsaken pit. A orange cactus stands tall near by. \nTheir is some light brown brush" + 
        " blowing in the wind to the east. \nThe sky is red... Darkness is coming soon.";
        locations[1] = "River";
        locations[2] = "Field";

        //Starting player location
        String player = locations[0];

        //This is how we will navigate the map
        // north + 1, east + 2, south -1, west - 2;
        //player = locations[0] + 1;

        String[] commands = new String[6];
        commands[0] = "investigate";
        commands[1] = "go north";
        commands[2] = "go east";
        commands[3] = "go south";
        commands[4] = "go west";
        commands[5] = "terminate game";

        System.out.println(locations[0]);

        do{
            input = scanner.nextLine();
            input = input.toLowerCase();

            if (input.equals(commands[0])) {
                // give description for location
                System.out.println(player);
            }

            if(input.equals(commands[1])){
                player = player + 1;
                System.out.println(player);
            }
            if(input.equals(commands[5])){
                break;
            }

        }
        while(running == true);
        System.exit(0);

    }

    }

3 个答案:

答案 0 :(得分:1)

语句player = player + 1正在使用字符串player并向其添加字符串1。所以,是的,它采取之前的player并在最后添加1

此处的关键是player属于String类型。因此它将"Location: ...." + 1视为"Location: ...." + "1" = "Location....1"

如果每次他们选择"去北方"它应该增加位置变量,那么你应该有一个int类型的位置变量。所以添加:

int loc = 0;

到初始化部分,将player = player + 1;行替换为两行

loc++;
player = locations[loc];

答案 1 :(得分:1)

实际上,变量"播放器"应该是一个int。在开始时将其设置为0。如果要打印玩家当前位置,请执行以下操作:

的System.out.println(地点[播放器]);

答案 2 :(得分:0)

我认为你应该将变量player定义为int

 int player =0;

然后打印location[player]