当前位置: 首页 > 工具软件 > Groovy PDF > 使用案例 >

Groovy pdf练习例子

印振国
2023-12-01


具体请下载:http://download.csdn.net/download/wuqilianga/10166448


GroovyTest

class GroovyTest {
	void test() {
		def names = ["Ted", "Fred", "Jed", "Ned"]
		println names
		def shortNames = names.findAll{ it -> it.size() <= 3 }
		println shortNames.size()
		shortNames.each{ it -> println it }
	}

	static void main(String[] args) {
		new GroovyTest().test()
	}
}

G1


class G1 {


	void test() {
		List list = new ArrayList();
		list.add(1);
		list.add(2);
		def have = false
		list.each{
			println("it的值是:$it")
		}
		for(it in list){
			println it;
			if(it>5) {
				have = true
				break;
			}
		}
		
		def names = ["Ted", "Fred", "Jed", "Ned"]
		println names
		def shortNames = names.findAll{ it.size() <= 3 }
		println shortNames.size()
		shortNames.each{ println it }
		
	}

	static void main(String[] args) {
		new G1().test()
	}
}

G2

class G2 {

	void test() {
		BikeGroovyBean bike = new G2$BikeGroovyBean();
		bike.setCost(new BigDecimal(100.11111111196))
		println bike.toString() 
	}

	static void main(String[] args) {
		new G2().test()
	}

	class BikeGroovyBean {
		String manufacturer, model, serialNo, status
		final Integer frame
		Double weight
		BigDecimal cost

		public void setCost(BigDecimal newCost) {
			cost = newCost.setScale(3, BigDecimal.ROUND_HALF_UP)
		}

		public String toString() {
			return """Bike:
manufacturer -- $manufacturer
model -- $model
frame -- $frame
serialNo -- $serialNo
"""
		}
	}
}

G3

class G3 {
	
	void test1(){
		// normal strings
		def firstname = 'Kate'
		def surname= "Bush"
		assert firstname * 2 == 'KateKate'
		// GString
		def fullname = "$firstname $surname"
		assert fullname == 'Kate Bush'
		assert fullname - firstname == ' Bush'
		assert fullname.padLeft(10) ==
		' Kate Bush'
		// indexing (including ranges)
		assert fullname[0..3] == firstname
		assert fullname[-4..-1] == surname
		assert fullname[5, 3..1] == 'Beta'
	}

	void test() {
		// normal strings
		def firstname = 'Kate'
		def surname= "Bush"
		assert firstname * 2 == 'KateKate'
		println firstname * 2 == 'KateKate'
		// GString
		def fullname = "$firstname $surname"
		assert fullname == 'Kate Bush'
		assert fullname - firstname == ' Bush'
		println fullname.padLeft(11)// == ' Kate Bush'
		// indexing (including ranges)
		assert fullname[0..3] == firstname
		println fullname[0..3]
		assert fullname[-4..-1] == surname
		println fullname[-4..-1]
		assert fullname[5, 3..1] == 'Beta'
		println fullname[5, 3..1,-8,-1]
		
		def address = """->
					$fullname
					123 First Ave
					New York
					""".trim()
		println address
		
		assert "吴" == "i"
		
		println "->lines:"

		def lines =
				address.split('\n')

		println lines
		
		assert "吴" == "黄"


	}

	static void main(String[] args) {
		new G3().test()
	}

}

G4
class G4 {


	void test() {
		
		def firstname = 'Kate'
		def surname= "Bush"
g		// GString
		def fullname = "$firstname $surname"
		
		// Multi-line strings
		def twister = '''\
		She sells, sea shells
		By the sea shore'''
		def lines =
				twister.split('\n')
		assert lines.size() == 2
		def address = """
		$fullname
		123 First Ave
		New York
		""".trim()
		def lines2 =
				address.split('\n')
		assert lines2.size() == 3

		// Multi-line strings
		def twister2 = '''\
		She sells, sea shells
		By the sea shore'''
		def lines3 =
				twister2.split('\n')
		assert lines3.size() == 2
		def address4 = """
		$fullname
		123 First Ave
		New York
		""".trim()
		def lines4 =
				address4.split('\n')
		assert lines4.size() == 3g


	}

	static void main(String[] args) {
		new G4().test()
	}
}


G5

class G5 {


	void test() {

		// more substrings
		def string = 'hippopotamus'
		assert string - 'hippo' - 'mus' + 'to' == 'potato'
		assert string.replace('ppopotam','bisc') == 'hibiscus'
		// processing characters
		assert 'apple'.toList() == ['a', 'p', 'p', 'l', 'e']
		//also: 'apple' as String[], 'apple'.split(''), 'apple'.each{}
		string = "an apple a day"
		assert string.toList().unique().sort().join() == ' adelnpy'
		// reversing chars/words
		assert 'string'.reverse() == 'gnirts'
		string = 'Yoda said, "can you see this?"'
		def revwords = string.split(' ').toList().reverse().join(' ')
		assert revwords == 'this?" see you "can said, Yoda'
		def words = ['bob', 'alpha', 'rotator', 'omega', 'reviver']
		def bigPalindromes = words.findAll{w -> w == w.reverse() && w.size() > 5}
		assert bigPalindromes == ['rotator', 'reviver']

	}

	static void main(String[] args) {
		new G5().test()
	}
}

G6

import static java.util.Calendar.getInstance as now
import java.text.SimpleDateFormat

import groovy.time.TimeCategory

class G6 {


	void test() {
		println now().time
		def date = new Date() + 1
		println date
		use(TimeCategory) {
			println new Date() + 1.hour + 3.weeks - 2.days
		}
		def input = "1998-06-03"
		def df1 = new SimpleDateFormat("yyyy-MM-dd")
		date = df1.parse(input)
		def df2 = new SimpleDateFormat("MMM/dd/yyyy")
		println 'Date was ' + df2.format(date)
	}

	static void main(String[] args) {
		new G6().test()
	}
}

G7

class G7 {


	void test() {

		def x = 3
		def y = 4
		assert x + y == 7
		assert x.plus(y) == 7
		assert x instanceof Integer
		assert 0.5 == 1/2 // uses BigDecimal arithmetic as default
		def a = 2 / 3 // 0.6666666666
		def b = a.setScale(3, BigDecimal.ROUND_HALF_UP)
		assert b.toString() == '0.667'
		assert 4 + 3 == 7 // 4.plus(3)
		assert 4 - 3 == 1 // 4.minus(3)
		assert 4 * 3 == 12 // 4.multiply(12)
		assert 4 % 3 == 1 // 4.mod(3)
		assert 4 ** 3 == 64 // 4.power(3)
		assert 4 / 3 == 1.3333333333 // 4.div(3)
		assert 4.intdiv(3) == 1 // normal integer division
		assert !(4 == 3) // !(4.equals(3))
		assert 4 != 3 // ! 4.equals(3)
		assert !(4 < 3) // 4.compareTo(3) < 0
		assert !(4 <= 3) // 4.compareTo(3) <= 0
		assert 4 > 3 // 4.compareTo(3) > 0
		assert 4 >= 3 // 4.compareTo(3) >= 0
		assert 4 <=> 3 == 1 // 4.compareTo(3)

	}

	static void main(String[] args) {
		new G7().test()
	}
}

G8
class G8 {


	void test() {

		/*Lists
		– Special syntax for list literals
		– Additional common methods (operator overloading)
		• Maps
		– Special syntax for map literals
		– Additional common methods
		• Ranges
		– Special syntax for various kinds of ranges
		Agile 2007 - 29
		Submission 631 © ASERT 2007
		def list = [3, new Date(), 'Jan']
		assert list + list == list * 2
		def map = [a: 1, b: 2]
		assert map['a'] == 1 && map.b == 2
		def letters = 'a'..'z'
		def numbers = 0..<10*/
		
		def list = [3, new Date(), 'Jan']
		assert list + list == list * 2
		def map = [a: 1, b: 2]
		assert map['a'] == 1 && map.b == 2
		def letters = 'a'..'z'
		def numbers = 0..<10
		
		assert [1,2,3,4] == (1..4)
		assert [1,2,3] + [1] == [1,2,3,1]
		assert [1,2,3] << 1 == [1,2,3,1]
		assert [1,2,3,1] - [1] == [2,3]
		assert [1,2,3] * 2 == [1,2,3,1,2,3]
		assert [1,[2,3]].flatten() == [1,2,3]
		assert [1,2,3].reverse() == [3,2,1]
		assert [1,2,3].disjoint([4,5,6])
		assert [1,2,3].intersect([4,3,1]) == [3,1]
		assert [1,2,3].collect{ it+3 } == [4,5,6]
		assert [1,2,3,1].unique().size() == 3
		assert [1,2,3,1].count(1) == 2
		assert [1,2,3,4].min() == 1
		assert [1,2,3,4].max() == 4
		assert [1,2,3,4].sum() == 10
		assert [4,2,1,3].sort() == [1,2,3,4]
		assert [4,2,1,3].findAll{ it%2 == 0 } == [4,2]
	}

	static void main(String[] args) {
		new G8().test()
	}
}

G9
class G9 {


	void test() {

		def map = [a:1, 'b':2]
		println map // ["a":1, "b":2]
		println map.a // 1
		println map['a'] // 1
		println map.keySet() // ["a", "b"]
		map = [:]
		// extend the map through assignment
		map[1] = 'a'; map[2] = 'b'
		map[true] = 'p'; map[false] = 'q'
		map[null] = 'x'; map['null'] = 'z'
		assert map == [ 1:'a', 2:'b', (true):'p',
			(false):'q', (null):'x', 'null':'z' ]
		def sb = new StringBuffer()
		[1:'a', 2:'b', 3:'c'].each{ k, v-> sb << "$k:$v, " }
		assert sb.toString() == '1:a, 2:b, 3:c, '
		map = [1:'a', 2:'b', 3:'c']
		def string = map.collect{ k, v -> "$k:$v" }.join(', ')
		assert string == '1:a, 2:b, 3:c'


		assert [
			[ name: 'Clark', city: 'London' ],
			[ name: 'Sharma', city: 'London' ],
			[ name: 'Maradona', city: 'LA' ],
			[ name: 'Zhang', city: 'HK' ],
			[ name: 'Ali', city: 'HK' ],
			[ name: 'Liu', city: 'HK' ]
		].groupBy { it.city } == [
			London: [[ name: 'Clark', city: 'London' ], [ name: 'Sharma', city: 'London' ]], LA: [[ name: 'Maradona', city: 'LA' ]], HK: [
				[ name: 'Zhang', city: 'HK' ],
				[ name: 'Ali', city: 'HK' ],
				[ name: 'Liu', city: 'HK' ]
			]
		]

		assert "Hello World!" =~ /Hello/ // Find operator
		assert "Hello World!" ==~ /Hello\b.*/ // Match operator
		def p = ~/Hello\b.*/ // Pattern operator
		assert p.class.name == 'java.util.regex.Pattern'
		// replace matches with calculated values
		assert "1.23".replaceAll(/./){ ch ->
			ch.next()
		} == '2/34'
		assert "1.23".replaceAll(/\d/){ num ->
			num.toInteger() + 1
		} == '2.34'
		assert "1.23".replaceAll(/\d+/){ num ->
			num.toInteger() + 1
		} == '2.24'

		def str = 'groovy.codehaus.org and www.aboutgroovy.com'
		def re = '''(?x) # to enable whitespace and comments
			( # capture the hostname in $1
			(?: # these parens for grouping only
			(?! [-_] ) # neither underscore nor dash lookahead
			[\\w-] + # hostname component
			\\. # and the domain dot
			) + # now repeat whole thing a few times
			[A-Za-z] # next must be a letter
			[\\w-] + # now trailing domain part
			) # end of $1 capture
			'''
		def finder = str =~ re
		def out = str
		(0..<finder.count).each{
			def adr = finder[it][0]
			out = out.replaceAll(adr,
					"$adr [${InetAddress.getByName(adr).hostAddress}]")
		}
		println out
		// => groovy.codehaus.org [63.246.7.187]
		// and www.aboutgroovy.com [63.246.7.76]
	}


	static void main(String[] args) {
		new G9().test()
	}
}

 更多。。。。请下载书籍学习。








 类似资料: