【问题标题】:Java: Converting number to binary and sorting from input classJava:将数字转换为二进制并从输入类排序
【发布时间】:2016-04-17 00:42:01
【问题描述】:

我无法将这些数字从输入文件转换为二进制。然后我想用最小的二进制数排序 个数排在第一位,个数最多的排在最后。如果两个 数字具有相同的个数,首先按以 10 为底的值对数字进行排序。 如果基数为 10 的值相同,则按原始值对数字进行排序。打印出原来的号码,它的 以 10 为底的值,最后以二进制打印出数字值。输入文件名 键盘。我必须使用 Comparable 接口。

如果有人可以帮助我将输入文件转换为二进制文件,那将很有帮助。

public static void main(String[] args) throws IOException {

    //Prompt the user and asks for filename. 
    System.out.print("Enter the file name: ");
    Scanner in = new Scanner(System.in);    
    String file = in.next();    //input file name


    //Takes input and reads from file. 
    Scanner input = new Scanner(new FileReader(file));
    for(int i = 0; i < 16; i++){

    // Input file read. 
    System.out.println(input.nextLine());

    } 

【问题讨论】:

  • 您的输入变量类型是什么?它们只是一个整数列表吗?
  • 是的,它是来自文本文件的整数列表
  • “原始数”和“以 10 为底的值”有什么区别?

标签: java sorting


【解决方案1】:

应该这样做:

List<BigInteger> numbers = new ArrayList<>();
new Scanner(new FileReader(new File(""))).forEachRemaining(s -> numbers.add(new BigInteger(s)));
numbers.sort(Comparator.<BigInteger>comparingLong(i -> i.toString(2).chars().filter(b -> b == '1').count())
                       .thenComparing(Function.identity()));
numbers.forEach(i -> System.out.format("%d - %s%n", i, i.toString(2)));

【讨论】:

    【解决方案2】:

    您首先应该将每一行保存为一个整数。由于是需要排序的列表,可以考虑使用数组。

    int[] array = new array[size];
    for (int i = 0; i < size; i++) {
        array[i] = input.nextLine();
    }
    

    然后您可以使用内置方法 Integer.toBinaryString。它将返回整数的变量类型字符串。

    String binary = Integer.toBinaryString(array[i])
    

    【讨论】:

      猜你喜欢
      • 2017-03-03
      • 2017-01-03
      • 2020-04-28
      • 2023-04-04
      • 1970-01-01
      • 2021-12-30
      • 2014-05-10
      • 1970-01-01
      • 2013-02-10
      相关资源
      最近更新 更多