How to read comma separated integer inputs in java

风格不统一 提交于 2019-12-19 03:08:50

问题


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:


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

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.

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




回答2:


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

Such as:

dis.useDelimiter("\\D");

The useDelimiter method takes a Pattern or the String representation of a 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

Output

1 2 3

Note

  • Don't forget to close your Scanner!
  • See the API for Patterns for additional fun delimiting your input.


来源:https://stackoverflow.com/questions/22936218/how-to-read-comma-separated-integer-inputs-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!