[英]How can I save a String, a Double, and an Integer from the same line using Java Scanner?
I have a.txt file where each line is formatted like so...我有一个 .txt 文件,其中每一行的格式如下...
pizza very cheesy 12.30 3
(each "item" is separated by a double space) pizza very cheesy 12.30 3
(每个“项目”由双空格分隔)
I tried using String[] itemInfo = scn.nextLine().split("\s ");
我尝试使用String[] itemInfo = scn.nextLine().split("\s ");
but that creates an array of each item as a String.但这会将每个项目的数组创建为字符串。
I need to save "pizza" and "very cheesy" as Strings , 12.30 as a Double , and 3 as Integer .我需要将“pizza”和“very cheesy”保存为Strings ,将 12.30 保存为Double ,将 3 保存为Integer 。 Any suggestions would be much appreciated.任何建议将不胜感激。
Cheers!干杯!
Call scanner.useDelimiter(" ");
调用scanner.useDelimiter(" ");
before you start reading.在你开始阅读之前。 That's TWO space characters between the quotes.这是引号之间的两个空格字符。 That way, your scanner will interpret the double space as the delimiter.这样,您的扫描仪会将双倍空格解释为分隔符。
Then you can use scanner.next()
for each of the name and the description, as well as scanner.nextDouble()
and scanner.nextInt()
after that.然后,您可以对每个名称和描述使用scanner.next()
,以及之后的scanner.nextDouble()
和scanner.nextInt()
。
Don't forget to use scanner.nextLine()
to consume the new line at the end of each line of data.不要忘记使用scanner.nextLine()
在每行数据的末尾使用新行。
The trick is using Arrays.copyOfRange()
to extract the rest part of the line.诀窍是使用Arrays.copyOfRange()
来提取该行的 rest 部分。 More details here .更多细节在这里。
public static void main(String[] args) {
String line = "pizza very cheesy 12.30 3";
String[] parts = line.split("\\s+");
String name = parts[0];
int count = Integer.parseInt(parts[parts.length - 1]);
double price = Double.parseDouble(parts[parts.length - 2]);
String description = String.join(
" ", Arrays.copyOfRange(parts, 1, parts.length - 2));
System.out.println("name: " + name +
"\ndescription: " + description +
"\nprice: " + price +
"\ncount: " + count
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.