使用扫描仪查找三个数字

时间:2013-01-03 01:14:27

标签: java java.util.scanner

我希望我的扫描仪读取.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并将其用作颜色?

3 个答案:

答案 0 :(得分: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));

或者,您可以使用Scanner API中的nextInt()方法直接将这些数字检索为int,但我会将其作为String s进入为了在适当的时候进行进一步的错误处理。

答案 1 :(得分: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);

如果没有,你需要澄清你的问题。

答案 2 :(得分:0)

当涉及到该特定行时,您可以使扫描程序使用.nextInt()方法三次,或者您可以编写一种方法,使用扫描程序方法{{1}从文本文件中检索整行并且有一个条件语句来检查该行是否包含.nextLine(),然后从字符串的其余部分解析整数。

杰夫的答案最适合您的需要。