Java 使用扫描仪查找三个数字

Java 使用扫描仪查找三个数字,java,java.util.scanner,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++){

我想让我的扫描仪读取一个
.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;
}

我怎样才能让它读懂
255 0 0
并将其用作一种颜色?

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

// 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);

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

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

// 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);

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

使用
扫描仪查找关键字,然后使用该关键字指示您希望继续处理的位置/方式

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
    }
 }
要将值转换为:


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

使用
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
    }
 }
要将值转换为:


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

您可以让扫描仪使用
.nextInt()
method在涉及到该特定行时执行三次,或者您可以编写一个方法,使用Scanner方法
.nextLine()从文本文件中检索整行
并有一个条件语句来检查该行是否包含
颜色:
,然后从字符串的其余部分解析整数。

Jeff的答案最适合您的需要。

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

Jeff的答案最适合您的需要。

您忘了问一个问题。请注意-当我想到连续整数时,我想到的是按顺序排列的
…整数。每两个数字之间的差值为1。(Wikipedia)。
所以,你不是在寻找连续整数,而是一组三个数字。RGB值之前是否总是会出现“颜色”一词?你忘了问一个问题。请注意,当我想到连续整数时,我想到的是按顺序排列的
…整数。每两个数字之间的差值为1。(Wikipedia)。
所以,你不是在寻找连续的整数,而是一组三个数字。RGB值之前是否总是会出现“颜色”一词?