1

我希望我的扫描仪读取.txt文件并找到三个整数int1 int2 int3并将它们用作颜色代码。唯一的问题是,我不知道该怎么做。

到目前为止,我有:

@SuppressWarnings("resource")

Scanner[] properties = new Scanner[str];
Color[] colour = new Color[str];

int posx = 200;
int posy = 100;

for (int i = 0; i < str; i++){
    properties[i] = new Scanner(new File("Particles/" + string[i] + ".txt"));
    g.drawString("Particles/" + string[i] + ".txt", 200, posy);
    colour[i] = new Color(properties[i].nextInt(), properties[i].nextInt(),properties[i].nextInt());
    posy = posy + 100;
}

(它只是方法的一部分,这就是为什么str没有声明等)。

我正在读取的文件看起来像:

Name:   Fire
Color:  255 0 0
Speed:  0
Size:   1

我如何让它阅读255 0 0并用作颜色?

4

3 回答 3

4

使用Scanner查找关键字,然后使用它来指示您希望在何处/如何继续处理。

String r, g, b;
Scanner scanner = new Scanner(myFile);
while(scanner.hasNext()) {
    String next = scanner.next();
    if(next.equals("Color:")) {
        r = scanner.next();
        g = scanner.next();
        b = scanner.next();
        // do stuff with the values
    }
 }

要将值转换为Colors

Color color = new Color(Integer.parseInt(r), Integer.parseInt(g), Integer.parseInt(b));

或者,您可以使用 API 中的nextInt()方法Scanner将数字直接检索为ints,但我会将它们作为Strings 接收,以便在适当的情况下执行进一步的错误处理。

于 2013-01-03T01:26:08.497 回答
1

我想你正在寻找这样的东西......

// lose the Name: line
scanner[i].nextLine()

// lose the Color: label
scanner[i].next()

// get the ints
int c1 = scanner[i].nextInt();
int c2 = scanner[i].nextInt();
int c3 = scanner[i].nextInt();

colour[i] = makeColor(c1, c2, c3);

如果不是,您需要澄清您的问题。

于 2013-01-03T01:25:36.650 回答
0

您可以让 Scanner.nextInt()对该特定行使用该方法三次,或者您可以编写一个方法来使用 Scanner 方法从文本文件中检索整行,.nextLine()并使用条件语句来检查该行是否包含Color:和然后从字符串的其余部分解析整数。

杰夫的回答将最适合您的需求。

于 2013-01-03T01:29:10.183 回答