How to read comma separated integer inputs in java

前端 未结 2 1608
一生所求
一生所求 2021-01-05 07:31
import java.io.*;
import java.util.*;
class usingDelimiters
{
    public static void main(String args[])
    {
        Scanner dis=new Scanner(System.in);
        in         


        
2条回答
  •  -上瘾入骨i
    2021-01-05 08:22

    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.

提交回复
热议问题