简体   繁体   English

使用扫描仪从列表中读取整数和字符串

[英]Read integers and string from a list using a scanner

I am reading a string from stdin that's formatted as a list. 我正在从标准输入格式读取的字符串中读取一个字符串。 I am using the information from the string to create objects. 我正在使用字符串中的信息来创建对象。

An example input string would be formatted as follows: 输入字符串示例的格式如下:

1 apple, 3 bananas, 2 pears

I want to read that line a create objects as I go, but my biggest issue is properly reading the line to get the number of items, followed by them item itself while also skipping whitespace and commas. 我想随即阅读该行创建对象,但我最大的问题是正确读取该行以获取项目数,其次是项目本身,同时还跳过空格和逗号。 I have tried the following: 我尝试了以下方法:

Scanner input = new Scanner(System.in);
input.useDelimeter(",|\\s");
while(input.hasNext()){
    int numItems = input.nextInt();
    String item = input.next();

    // create object and add to object array
}

Which works for the first iteration (1 apple) but fails on the second with a type mismatch. 它适用于第一次迭代(一个苹果),但在第二次迭代中由于类型不匹配而失败。 Can anyone suggest a fix or alternate solution? 谁能建议修复或替代解决方案?

Thanks! 谢谢!

,|\\\\s declares two separate delimiters. ,|\\\\s声明两个单独的定界符。 Those delimiters can be matched in text "apple, 3" twice: 这些定界符可以在文本"apple, 3"匹配两次:

  1. comma after apple apple后的逗号
  2. space before 3 3之前的空格

    apple, 3 ^^ 12 苹果3 ^^ 12

so we split that text at two separate (middle) places, which means we split it into 3 tokens: 因此我们将文本拆分为两个单独的(中间)位置,这意味着我们将其拆分为3个标记:

  • "apple" , "apple"
  • "" , ""
  • "3" . "3"

When in next iteration (after calling input.next() which consumes apple ) you are calling input.nextInt() Scanner tries to parse second token as int, but since it finds empty string it is throwing exception. 在下一次迭代中(调用消耗了apple input.next()之后input.next() ,您正在调用input.nextInt()扫描程序尝试将第二个标记解析为int,但是由于找到空字符串,因此抛出异常。

One of solutions would be treating [space] or ,[space] as single delimiter. 解决方案之一是将[space],[space]视为单个定界符。 You can achieve it by making comma optional: 您可以通过使逗号为可选来实现:

input.useDelimiter(",?\\s");

Demo: 演示:

Scanner input = new Scanner("1 apple, 3 bananas, 2 pears");
input.useDelimiter(",?\\s");
while(input.hasNext()){
    int numItems = input.nextInt();
    System.out.println(numItems);
    String item = input.next();
    System.out.println(item);
    System.out.println("----");
}

Output: 输出:

1
apple
----
3
bananas
----
2
pears
----

You can spilt the input String using delimiter "," and get following output after using trim() method. 您可以使用定界符“,”溢出输入String,并在使用trim()方法后获得以下输出。

1 apple 1个苹果

3 bananas 3根香蕉

2 pears 2个梨

Here is the code: 这是代码:

 String [] array1 = input.nextLine().split(",");

 for(int i=0; i<array1.length; i++){
    System.out.println(array1[i].trim());
 }

Edit: You can further split the Strings inside for loop using delimiter space , to get the desired output. 编辑:您可以使用定界符space进一步在for loop内拆分Strings,以获得所需的输出。

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

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