【问题标题】:How to short a string array, but keep the format of the entire line in JAVA [closed]如何缩短字符串数组,但在JAVA中保持整行的格式[关闭]
【发布时间】:2017-11-03 15:08:13
【问题描述】:

我想用字符串缩短一个数组,但我不能保持字符串的整个格式不变......

例如我有这个数组:

        String A={ 0.01%%name1 , 0.5%%name2, 1.0%%name3  0.6%%name4,  1.2%%name5}

我想像这样对一个字符串数组( x[ ] )进行排序:

                                     1.2  name5
                                     1.0  name3
                                     0.6  name4
                                     0.5  name2
                                     0.01 name1

到目前为止,此代码进行了排序,但名称似乎没有排序。有什么想法吗?

  String[] top5Matches = new String[10];
  for(int i=0;i<10;i++){
  String[] parts = x[i].split("%%"); 
  top5Matches[i]=parts[0];   
   }
  Arrays.sort(top5Matches);
 for(int i=0;i<Database_len;i++)
   {
      System.out.println(top5Matches[i]);   
   }

目前的结果......

     0.01
     0.05
     0.05
     1.0
     1.2

【问题讨论】:

  • 那么,您想按数字部分降序排序吗?
  • 您只需要对数组进行排序还是根据预期结果转换值?
  • 当你向别人展示代码时..请格式化..
  • 实际上是升序,但我可以用两种方式处理它
  • 好的@Tim Castelijns,因为这是我的第一篇文章,当你说格式化时? (我必须改变什么?)

标签: java arrays string sorting quicksort


【解决方案1】:

编写一些模型类,例如 (或使用 Map)

class Element {
    String name;
    float value;
}

创建元素并添加到数组中:

Element el1 = new Element();
Element el2 = new Element();

按值(或您想要的其他方式)对数组进行排序并打印结果。

For(Element el: elements){
    System.out.pritnln(el.value + "\t" + el.name)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2012-01-25
    相关资源
    最近更新 更多