scanner无法读取字符串中的最后一个int

时间:2016-02-09 05:06:46

标签: java string int java.util.scanner

    if (diceValues == null || diceValues.length() == 0) return 0;
    int temp;
    int val = 0;
    Scanner scanner = new Scanner(diceValues);
    while (scanner.hasNext()) {
        temp = scanner.useDelimiter(" ").nextInt();
        if (temp == 1) val += 100;
        if (temp == 5) val += 50;
    }

diceValue是这样的字符串:" 1 2 3 4 5",扫描仪总是跳过最后一个数字。所以int val(值)总是小于它应该是。

1 个答案:

答案 0 :(得分:1)

我认为你的代码没有问题。我以这种方式运行它,它返回值150。

import java.util.Scanner;
public class Prog1 
{
    public static void main(String[] args){
        Prog1 p =new Prog1();
        int value = p.mymethod();
        System.out.println(value);
    }
    public int mymethod()
    {
        String diceValues = "1 2 3 4 5";
        if (diceValues == null || diceValues.length() == 0) return 0;
        int temp;
        int val = 0;
        Scanner scanner = new Scanner(diceValues);
        while (scanner.hasNext()) {
        temp = scanner.useDelimiter(" ").nextInt();
            if (temp == 1) val += 100;
            if (temp == 5) val += 50;
        }
        return val;
    }