【问题标题】:scanner cannot read last int from a string扫描仪无法从字符串中读取最后一个 int
【发布时间】:2016-05-18 23:32:08
【问题描述】:
    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(value) 总是比它应该的小。

【问题讨论】:

  • 你是否正确调试了这个程序,因为我可以看到所有值都从扫描仪中正确读取
  • 你怎么知道它跳过了最后一个数字?我刚刚用System.out.println(temp) 试了一下,它显示了所有 5 个数字。

标签: java string int java.util.scanner


【解决方案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;
    }

【讨论】:

  • 谢谢,那我应该寻找我的程序的其他部分。
猜你喜欢
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
相关资源
最近更新 更多