在Java中循环,从String中获取2个值

时间:2016-03-09 03:42:32

标签: java string loops input delimiter

我需要编写一个循环,从用户给定的列表中获取两个值,然后在循环中使用这些值。我的问题是我似乎无法从循环中获取String中的2个值。 这是我的代码:

import java.util.Scanner;

public class practice2 {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        System.out.println("enter numbers seperated by commas");
        String numbers = input.nextLine();
        Scanner s = new Scanner(numbers);
        s.useDelimiter(",");
        for(int i =0; i<numbers.length(); i+=2 ) {
            int newnum = i/25;
            System.out.println(newnum);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在这里,要获取值 - 按以下步骤

public static void main(String[] args) {
    System.out.println("enter numbers seperated by commas");
    Scanner input = new Scanner (System.in);
    String[] numbers = input.nextLine().split(",\\s*");

    //to read number
    System.out.println(numbers[0] + " - " + numbers[1]);

    //to use them as int
    int i = Integer.parseInt(numbers[0]);
    System.out.println(++i);

}