java - 终止程序 -1 -1 输入不起作用

标签 java

我正在做一些 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();

        }
    }
}

最佳答案

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

程序未终止的可能原因:

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

  2. 您输入“-1”值的方式是否会向输入流添加一个或多个尾随字符,导致扫描仪读取除 -1 以外的值?

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

关于java - 终止程序 -1 -1 输入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215559/

相关文章:

java - 转换类没有效果

java - Springboot在实现Web安全和mvc配置后不会加载CSS文件夹

java - 使用 Java Apache POI 在 Excel 数据透视表中对包含日期和时间的列(按日期、月份和年份)进行分组

java - Spring Cloud Stream Test 在消息负载中硬编码 "Hello World"

java - Spring Data JPA 关系注释

java - Hadoop - java.net.BindException : Address already in use

java - Android if/else无法停止发布JSON

java - 未记录的 Java 命令行选项?

Java,创建并修改作为参数传递给新对象的构造函数的对象

java - 插件开发: create new file dialog using FileDialog