1

为了好玩,我正在做一些 ICPC 编程问题,这是 Collat​​z。我得到了一个正确符合预期输出的输出。但是当涉及到 -1 -1 输入时,我一直无法让程序根据需要结束。

样本输入

3 100
34 100
75 250
27 2147483647
101 304
101 303
-1 -1

预期产出

Case 1: A = 3, limit = 100, number of terms = 8 

Case 2: A = 34, limit = 100, number of terms = 14 

Case 3: A = 75, limit = 250, number of terms = 3  

Case 4: A = 27, limit = 2147483647, number of terms = 112

Case 5: A = 101, limit = 304, number of terms = 26 

Case 6: A = 101, limit = 303, number of terms = 1

Java 代码

import java.util.Scanner;
import java.lang.Integer;

public class Collatz {
    private static int caseNumber = 0;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            caseNumber++;
            int a = in.nextInt();
            Integer limit = in.nextInt();
            if(a == -1 && limit == -1)
                break;
            int numberOfTerms = 0;
            for(Integer value = a; value != 1; numberOfTerms++){
                if(value%2 == 0){
                    value /= 2;
                }else{
                    value = 3 * value + 1;
                }
                if(limit < value)
                    break;
            }
            numberOfTerms +=1;
            System.out.println("Case " + caseNumber + ": A = " + a + ", limit = "
                    + limit + ", number of terms = " + numberOfTerms);
            System.out.println();

        }
    }
}
4

1 回答 1

0

在 Eclipse (3.7.2) 中运行代码并在控制台窗口中输入值,它运行良好并按预期终止。(即输入两次“-1”时)

程序未终止的可能原因:

  1. Scanner 根据系统的默认字符集将字节转换为字符。您的系统字符集是否会导致“-1”转换为预期值以外的值?

  2. 您用于输入“-1”值的方式是否会在输入流中添加一个或多个尾随字符,从而导致扫描器读取 -1 以外的值?

尝试在每次调用后添加打印语句in.nextInt()以查看生成的值。

于 2012-04-18T19:43:07.790 回答