简体   繁体   English

Java-使用扫描仪读取同一行上的多个项目

[英]Java - Using scanner to read multiple items on the same line

I'm trying to load in a text file that is formatted like so: 我正在尝试加载格式如下的文本文件:

 int String int

 int String int

 int String int

What I want to do is to read the three values and put them into a constructor 我要做的是读取三个值并将它们放入构造函数中

My usual approach to a problem like this would be to simply do 我通常对这种问题的处理方法是

        int t = infile.nextInt();
        String d = infile.nextLine();
        int p = infile.nextInt();


        Entry e = new Entry(t,d,p);

However, this only works if t,d and p are on separate lines because of nextInt() and nextLine() 但是,这仅在由于nextInt()和nextLine()而使t,d和p位于单独的行上时有效

My question is, how do I proceed to read in the 3 values from the same line, and then move on to the next line? 我的问题是,如何继续从同一行读取3个值,然后继续进行下一行?

Parse it like this: 像这样解析它:

int t = infile.nextInt(); //reads int
String d = infile.next(); //reads the next String before a blank space " "
int p = infile.nextInt(); //reads int
Entry e = new Entry(t,d,p); //use your data
infile.nextLine(); //read the line escape "\n" or "\r\n"

I would read the entire line as a String, tokenize it at whitespace, and parse out the three values into their appropriate types: 我将整行读取为String,在空白处将其标记化,然后将这三个值解析为相应的类型:

String line = infile.nextLine();
String [] tokens = line.split("\\s+");
int v1 = Integer.parseInt(tokens[0]);
String v2 = tokens[1];
int v3 = Integer.parseInt(tokens[2]);
Entry e = new Entry(v1, v2, v3);

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

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