我没有使用cmd .prompt在java中获得正确的输出

时间:2016-09-25 19:02:59

标签: java java-8

对于大量输入,最后输入的输出不显示。 当我习惯输入15个或更多不同的输入时,我得到的输出比给定的输出数少一个。未显示的输出是最后一个输出。

 Scanner sc = new Scanner(System.in);
    int t=sc.nextInt();

    while(sc.hasNext())
    {

        try
        {
            long x=sc.nextLong();
            System.out.println(x+" can be fitted in:");
            if(x>=-128 && x<=127)System.out.println("* byte");
            if(x>=-pow(2,15) && x<pow(2,15))System.out.println("* short");
            if(x>=-(long)pow(2,31) && x<(long)pow(2,31))System.out.println("* int");
            if(x>=-(long)pow(2,63) && x<(long)pow(2,63))System.out.println("* long");

            //Complete the code
        }
        catch(Exception e)
        {
            System.out.println(sc.next()+" can't be fitted anywhere.");
        }

    }

1 个答案:

答案 0 :(得分:0)

我想,你的代码的第二行应该解释输入中缺少的数字。您从输入中读取第一个数字,然后不执行任何操作:

int t=sc.nextInt();

但是您的代码存在更多问题。 从铸造到(长)判断你是在这些方面做的:

        if(x>=-(long)pow(2,31) && x<(long)pow(2,31))System.out.println("* int");
        if(x>=-(long)pow(2,63) && x<(long)pow(2,63))System.out.println("* long");

我猜测您的pow函数不会返回long,但可能会int。也许你在pow函数内做的计算也是在整数上完成的。这将导致整数溢出并返回不正确的结果。您应该将它们更改为long

另外,您尝试计算的最后一个值 - pow(2,63) - 可以t fit even into长,因此您无法计算它。我改为使用Long.MAX_VALUE建议。