我正在做一些 ICPC 编程问题来娱乐,这个问题是 Collatz。我得到了一个与预期输出正确匹配的输出。但是当涉及到所需的 -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();
}
}
}
最佳答案
在 Eclipse (3.7.2) 中运行代码并在控制台窗口中输入值,它运行良好并按预期终止。 (即当输入“-1”两次时)
程序未终止的可能原因:
扫描程序根据系统的默认字符集将字节转换为字符。您的系统字符集是否会导致“-1”转换为预期值以外的值?
您输入“-1”值的方式是否会向输入流添加一个或多个尾随字符,导致扫描仪读取除 -1 以外的值?
尝试在每次 in.nextInt()
调用后添加 print 语句,以查看生成的值。
关于java - 终止程序 -1 -1 输入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215559/