20155201 第十二周课堂实践

it2022-05-09  35

一、

测试Arrays类中Sort方法和BinSearch方法

import junit.framework.TestCase; import org.junit.Test; import java.util.Arrays; public class ArrayclassTest extends TestCase { int[] score={1,2,4,5}; @Test public void testSort(){ Arrays.sort(score); assertEquals(4,score[2]); } @Test public void testbinarySearch(){ Arrays.sort(score); assertEquals(0,Arrays.binarySearch(score,1)); assertEquals(-5,Arrays.binarySearch(score,6)); } }

测试String类中的charAt方法和split方法

import junit.framework.TestCase; import org.junit.Test; import java.lang.*; public class StringclassTest extends TestCase { String buffer="Stri,n,g"; String[] sp=buffer.split(","); @Test public void testCharAt(){ assertEquals('S',buffer.charAt(0)); } @Test public void testsplit(){ assertEquals("Stri",sp[0]); } }

二、

实现Linux内sort -k2功能

import java.util.*; public class MySort1 { public static void main(String[] args) { String[] toSort = {"aaa:10:1:1", "ccc:30:3:4", "bbb:50:4:5", "ddd:20:5:3", "eee:40:2:20"}; int[] tmp=new int[toSort.length]; String[] sp=new String[toSort.length]; for(int i=0;i<toSort.length;i++){ sp=toSort[i].split(":"); tmp[i]=Integer.parseInt(sp[1]); } for(int i=0;i<toSort.length-1;i++){ for(int j=i+1;j<toSort.length;j++){ if (tmp[i] > tmp[j]) { String temp=toSort[i]; toSort[i]=toSort[j]; toSort[j]=temp; int tp=tmp[i]; tmp[i]=tmp[j]; tmp[j]=tp; } } } for(int i=0;i<toSort.length;i++){ System.out.println(toSort[i]); } } }

转载于:https://www.cnblogs.com/zhuohua/p/6853738.html


最新回复(0)