如何在java中读取逗号分隔的整数输入 [英] How to read comma separated integer inputs in java

查看:308
本文介绍了如何在java中读取逗号分隔的整数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
    }
}

当输入为1时,此程序工作正常3(以空格分隔)
但是,当我的输入是1,2,3(用逗号分隔)时如何修改我的程序

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)

推荐答案

你可以使用nextLine方法读取一个String并使用split这个方法用逗号分隔,如下所示:

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);
    }

此方法将使用以逗号分隔的3个值。

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.

这篇关于如何在java中读取逗号分隔的整数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆