繁体   English   中英

学校 Java 密室逃脱计划

[英]School Java Escape Room Program

我正在为学校编写一个逃生室项目,其中包含诸如问候、获胜消息、丢失消息等消息。我将这些消息存储在一个文本文件中,然后读取该文件并将每一行存储到一个 ArrayList 中,然后通过各自的 getter 方法访问每一行,我使用.get函数及其索引值。 我想知道是否有办法避免对索引号进行硬编码,最重要的是,有没有一种方法可以在程序运行时读取文件,而不必创建类的实例,然后例如执行foo.readFile();

import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.ArrayList;
//package Stage;

public class EscapeRoom{

    ArrayList<String> Messages;
    String fileName;
    private boolean win = false;

    public void readFile() throws FileNotFoundException {

        Messages = new ArrayList<String>();
        fileName = "test.txt";
        
        File file = new File(fileName); 
        Scanner scanner = new Scanner(file);
        while(scanner.hasNextLine()){
            Messages.add(scanner.nextLine());
        }
        scanner.close();

    }   
    
    public void showGreeting(){
        System.out.println(Messages.get(0));
    }
    public void showDirections(){
        System.out.println(Messages.get(1));
    }
    public void showWin() {
        System.out.println(Messages.get(2));
    }
    public void showLoss() {
        System.out.println(Messages.get(3));
    }
}

这正是属性文件的用途。 这是我命名为 prompts.properties 的文件:

greeting = "hello, welcome to my game"
win = "you win, yay"
loss = "sorry bro, you lose"
directions = "escape with your life!"

这是您修改后的程序:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class EscapeRoom {

    Properties prompts = null;

    public void readFile() throws IOException {
        prompts = new Properties();
        prompts.load(new FileInputStream("prompts.properties"));
    }

    public void showGreeting() {
        System.out.println(prompts.get("greeting"));
    }

    public void showDirections() {
        System.out.println(prompts.get("directions"));
    }

    public void showWin() {
        System.out.println(prompts.get("win"));
    }

    public void showLoss() {
        System.out.println(prompts.get("loss"));
    }
}

基本上要获得一个命名的键值对,你需要像地图这样的东西。 属性实际上是一种特殊的映射,它理解具有<key> = <value>格式的记录文件。

这是关于Properties的文档,如果您决定自己动手,您将使用Map实现相同的基本内容。

暂无
暂无

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

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