如何在java中读取逗号分隔的整数输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22936218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:23:16  来源:igfitidea点击:

How to read comma separated integer inputs in java

javajava.util.scannerdelimiter

提问by user3126841

import java.io.*;
import java.util.*;
class usingDelimiters
{
    public static void main(String args[])
    {
        Scanner dis=new Scanner(System.in);
        int a,b,c;
        a=dis.nextInt();
        b=dis.nextInt();
        c=dis.nextInt();
        System.out.println("a="+a);
        System.out.println("b="+b);
        System.out.println("c="+c);
    }
}

This program is working fine when my input is 1 2 3 (separated by space) But, how to modify my program when my input is 1,2,3 (separated by commas)

当我的输入为 1 2 3(以空格分隔)时,该程序运行良好但是,当我的输入为 1,2,3(以逗号分隔)时如何修改我的程序

采纳答案by Tiago Vieira Dos Santos

you can use the nextLine method to read a String and use the method split to separate by comma like this:

您可以使用 nextLine 方法读取字符串并使用 split 方法以逗号分隔,如下所示:

public static void main(String args[])
    {
        Scanner dis=new Scanner(System.in);
        int a,b,c;
        String line;
        String[] lineVector;

        line = dis.nextLine(); //read 1,2,3

        //separate all values by comma
        lineVector = line.split(",");

        //parsing the values to Integer
        a=Integer.parseInt(lineVector[0]);
        b=Integer.parseInt(lineVector[1]);
        c=Integer.parseInt(lineVector[2]);

        System.out.println("a="+a);
        System.out.println("b="+b);
        System.out.println("c="+c);
    }

This method will be work with 3 values separated by comma only.

此方法仅适用于以逗号分隔的 3 个值。

If you need change the quantity of values may you use an loop to get the values from the vector.

如果您需要更改值的数量,您可以使用循环从向量中获取值。

回答by Mena

You can use a delimiter for non-numerical items, which will mark any non-digit as delimiter.

您可以为非数字项目使用分隔符,它将任何非数字标记为分隔符。

Such as:

如:

dis.useDelimiter("\D");

The useDelimitermethod takes a Patternor the Stringrepresentation of a Pattern.

useDelimiter方法采用 aPattern或a的String表示Pattern

Full example:

完整示例:

Scanner dis=new Scanner(System.in);
dis.useDelimiter("\D");
int a,b,c;
a=dis.nextInt();
b=dis.nextInt();
c=dis.nextInt();
System.out.println(a + " " + b + " " + c);
dis.close();

Inputs (either or)

输入(或)

  • 1,2,3
  • 1 2 3
  • 1,2,3
  • 1 2 3

Output

输出

1 2 3

Note

笔记

  • Don't forget to closeyour Scanner!
  • See the APIfor Patterns for additional fun delimiting your input.
  • 不要忘记close你的Scanner
  • 请参阅s的APIPattern获得更多乐趣来分隔您的输入。