Javalatex 程序代码码!

eclipse如何编写java程序_百度经验
&&&&&&&&&电脑软件eclipse如何编写java程序听语音1234567
百度经验:初次接触java的同学都是用cmd打程序,那么用eclipse如何编写java程序百度经验:系统:win7工具:eclipse百度经验:1打开eclipse如图:2打开主界面,新建一个工程,如图:3输入名字,如“例子”,如图:4找到“例子”程序,找到src,点击右键,新建一个java程序,如图:5起个名,如“out”,如图:6看看我们新建的java程序,如图:7然后编写代码,如图:8点击上图红色区域的运行按钮,得到如图:END经验内容仅供参考,如果您需解决具体问题(尤其法律、医学等领域),建议您详细咨询相关领域专业人士。作者声明:本篇经验系本人依照真实经历原创,未经许可,谢绝转载。投票(14)已投票(14)有得(0)我有疑问(0)◆◆说说为什么给这篇经验投票吧!我为什么投票...你还可以输入500字◆◆只有签约作者及以上等级才可发有得&你还可以输入1000字◆◆如对这篇经验有疑问,可反馈给作者,经验作者会尽力为您解决!你还可以输入500字相关经验7212620热门杂志第1期你不知道的iPad技巧3593次分享第1期win7电脑那些事6274次分享第2期新人玩转百度经验1239次分享第1期Win8.1实用小技巧2566次分享第1期小白装大神1752次分享◆请扫描分享到朋友圈记住登录一个月发表随想还能输入:200字该用户最新代码编程随想&by by by by by by [java]代码库
import java.awt.C
import java.awt.F
import java.awt.G
import java.awt.event.KeyE
import java.awt.event.KeyL
import java.io.F
import java.io.FileInputS
import java.util.ArrayL
import java.util.R
import javax.swing.BorderF
import javax.swing.ImageI
import javax.swing.JF
import javax.swing.JP
import tankwar.Tank.D
import barrier.EnemyB
import barrier.G
import barrier.H
import barrier.I
import barrier.SelfB
import barrier.W
public class TankWar implements KeyListener {
static boolean TIMEOUT =
private JF
private JPanel gameP
private PanelShow messgeP
private myP
private Tank myT
public static final int AREA_WIDTH = 830;
public static final int AREA_HEIGHT = 800;
private ArrayList&Missle& missles = new ArrayList&Missle&();
private ArrayList&Tank& allTanks = new ArrayList&Tank&();
private ArrayList&Boom& booms = new ArrayList&Boom&();
private ArrayList&Wall& walls = new ArrayList&Wall&();
private ArrayList&Iron& irons = new ArrayList&Iron&();
private ArrayList&Gold& golds = new ArrayList&Gold&();
private ArrayList&Item& items = new ArrayList&Item&();
private ArrayList&EnemyBorn& enemyBorns = new ArrayList&EnemyBorn&();
private SelfBorn selfB
private Tank enemyT
private ImageIcon backG
private final S
private int tankM
private boolean over =
private static int selfMax = 3;
private boolean flash =
private TankWar tw =
static int SCORE = 0;
private final JFrame mainF;
public TankWar(String map, int tankMax, JFrame mainF, int style)
throws Exception {
this.map =
this.tankMax = tankM
this.mainF = mainF;
this.style =
private void init() {
f = new JFrame("坦克大战 V3.0");
gamePanel = new JPanel(null);
p = new myPanel();
p.setBackground(Color.WHITE);
r = new Random();
messgePanel = new PanelShow();
initMap(new File("map/" + map));
myTank = new Tank(selfBorn.getX(), selfBorn.getY(), true, allTanks,
walls, irons, golds, missles, home, booms, style);
} catch (Exception e1) {
myTank.setDir(Direction.U);
allTanks.add(myTank);
addTank();
backGround = new ImageIcon(
TankWar.class.getResource("/pic/whiteback.jpg"));
} catch (Exception e) {
p.setBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.WHITE));
p.setSize(AREA_WIDTH, AREA_HEIGHT);
messgePanel.setBounds(AREA_WIDTH, 0, 200, AREA_HEIGHT);
gamePanel.add(messgePanel);
gamePanel.add(p);
f.add(gamePanel);
f.setBounds(0, 0, AREA_WIDTH + 200, AREA_HEIGHT);
f.setDefaultCloseOperation(3);
f.setResizable(true);
f.setFocusable(true);
f.addKeyListener(this);
f.setVisible(true);
new Thread(new Runnable() {
public void run() {
while (!over) {
if (!myTank.isLive()) {
selfMax--;
if (selfMax & 0) {
f.removeKeyListener(tw);
myTank.setLevel(1);
myTank.setX(selfBorn.getX());
myTank.setY(selfBorn.getY());
myTank.setDir(Direction.U);
myTank.setHp(50);
myTank.setLive(true);
if (tankMax &= 0 && allTanks.size() == 1) {
f.removeKeyListener(tw);
if (!home.isLive()) {
f.removeKeyListener(tw);
p.repaint();
myTank.move();
for (int i = 1; i & allTanks.size(); i++) {
allTanks.get(i).move();
allTanks.get(i).setNoFire(myTank.getNoFire() + 1);
// if(allTanks.get(i).getX()%5==0&&allTanks.get(i).getY()%5==0)
aI(allTanks.get(i));
if (allTanks.size() &= enemyBorns.size() + 1)
addTank();
myTank.setNoFire(myTank.getNoFire() + 1);
messgePanel.setEnemyCount(tankMax);
messgePanel.setSelfCount(selfMax);
messgePanel.setScore(SCORE);
if (SCORE % 500 == 0) {
SCORE += 100;
Item item = new Item(allTanks, booms, irons, home);
items.add(item);
item.start();
Thread.sleep(30);
} catch (InterruptedException e) {
}).start();
private class myPanel extends JPanel {
private static final long serialVersionUID = 7225328L;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backGround.getImage(), 0, 0, null);
for (int j = 0; j & walls.size(); j++) {
walls.get(j).draw(g);
for (int j = 0; j & irons.size(); j++) {
irons.get(j).draw(g);
for (int j = 0; j & golds.size(); j++) {
golds.get(j).draw(g);
for (int j = 0; j & enemyBorns.size(); j++) {
enemyBorns.get(j).draw(g);
home.draw(g);
selfBorn.draw(g);
for (int j = 0; j & allTanks.size(); j++) {
allTanks.get(j).drawTank(g);
for (int j = 0; j & irons.size(); j++) {
irons.get(j).draw(g);
for (int i = 0; i & missles.size(); i++) {
missles.get(i).drawMissle(g);
if (!missles.get(i).isLive())
missles.remove(i);
for (int i = 0; i & booms.size(); i++) {
if (booms.get(i).isLive())
booms.get(i).drawBoom(g);
booms.remove(i);
for (int j = 0; j & items.size(); j++) {
if (!items.get(j).isLive()) {
items.remove(j);
items.get(j).draw(g);
drawOver(g);
messgePanel.repaint();
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
public void keyPressed(KeyEvent e) {
if (over) {
if (e.getKeyCode() == KeyEvent.VK_F1) {
missles.clear();
allTanks.clear();
booms.clear();
walls.clear();
irons.clear();
golds.clear();
enemyBorns.clear();
} catch (Exception e1) {
f.setVisible(false);
mainF.setSize(800, 800);
mainF.setVisible(true);
} else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
myTank.fire();
myTank.keyPress(e);
public void keyReleased(KeyEvent e) {
myTank.keyReleased(e);
public void aI(Tank tank) {
if (TIMEOUT) {
tank.setUp(false);
tank.setLeft(false);
tank.setDown(false);
tank.setRight(false);
if (r.nextInt(40) == 0)
tank.fire();
if (r.nextInt(10) == 0) {
if (tank.getX() &= myTank.getX()
&& tank.getX() &= myTank.getX() + Tank.SIZE
&& tank.getY() & myTank.getY()) {
tank.setUp(true);
tank.setLeft(false);
tank.setDown(false);
tank.setRight(false);
tank.setDir(Direction.U);
} else if (tank.getX() &= myTank.getX()
&& tank.getX() &= myTank.getX() + Tank.SIZE
&& tank.getY() & myTank.getY()) {
tank.setUp(false);
tank.setLeft(false);
tank.setDown(true);
tank.setRight(false);
tank.setDir(Direction.D);
else if (tank.getX() & myTank.getX()
&& tank.getY() &= myTank.getY()
&& tank.getY() &= myTank.getY() + Tank.SIZE) {
tank.setUp(false);
tank.setLeft(true);
tank.setDown(false);
tank.setRight(false);
tank.setDir(Direction.L);
} else if (tank.getX() & myTank.getX()
&& tank.getY() &= myTank.getY()
&& tank.getY() &= myTank.getY() + Tank.SIZE) {
tank.setUp(false);
tank.setLeft(false);
tank.setDown(false);
tank.setRight(true);
tank.setDir(Direction.R);
if (tank.getX() &= 0) {
tank.setUp(false);
tank.setLeft(false);
tank.setDown(false);
tank.setRight(true);
tank.setDir(Direction.R);
if (tank.getY() &= 0) {
tank.setUp(false);
tank.setLeft(false);
tank.setDown(true);
tank.setRight(false);
tank.setDir(Direction.D);
if (tank.getX() &= AREA_WIDTH - Tank.SIZE) {
tank.setUp(false);
tank.setLeft(true);
tank.setDown(false);
tank.setRight(false);
tank.setDir(Direction.L);
if (tank.getY() &= AREA_HEIGHT - Tank.SIZE) {
tank.setUp(true);
tank.setLeft(false);
tank.setDown(false);
tank.setRight(false);
tank.setDir(Direction.U);
} else if (r.nextInt(300) == 1) {
tank.setUp(true);
tank.setLeft(false);
tank.setDown(false);
tank.setRight(false);
tank.setDir(Direction.U);
else if (r.nextInt(300) == 2) {
tank.setUp(false);
tank.setLeft(true);
tank.setDown(false);
tank.setRight(false);
tank.setDir(Direction.L);
} else if (r.nextInt(300) == 3) {
tank.setUp(false);
tank.setLeft(false);
tank.setDown(true);
tank.setRight(false);
tank.setDir(Direction.D);
} else if (r.nextInt(300) == 4) {
tank.setUp(false);
tank.setLeft(false);
tank.setDown(false);
tank.setRight(true);
tank.setDir(Direction.R);
public void initMap(File file) {
FileInputStream read = new FileInputStream(file);
for (int i = 0; i & AREA_HEIGHT / 50; i++) {
for (int j = 0; j & AREA_WIDTH / 50; j++) {
switch (read.read()) {
walls.add(new Wall(j * 50, i * 50));
irons.add(new Iron(j * 50, i * 50));
golds.add(new Gold(j * 50, i * 50));
selfBorn = new SelfBorn(j * 50, i * 50);
enemyBorns.add(new EnemyBorn(j * 50, i * 50));
home = new Home(j * 50, i * 50);
read.close();
} catch (Exception e) {
public void addTank() {
if (tankMax &= 0)
for (int i = allTanks.size(); i & enemyBorns.size() + 1; i++) {
int temp = r.nextInt(enemyBorns.size());
enemyTank = new Tank(enemyBorns.get(temp).getX(), enemyBorns
.get(temp).getY(), false, allTanks, walls, irons,
golds, missles, home, booms, r.nextInt(3) + 1);
} catch (Exception e) {
e.printStackTrace();
enemyTank.setDir(Direction.D);
enemyTank.setDown(true);
allTanks.add(enemyTank);
tankMax--;
if (tankMax &= 0)
public static void addMyTankLives() {
selfMax++;
private void over() {
for (int i = 0; i & AREA_HEIGHT / 50; i++) {
for (int j = 0; j & AREA_WIDTH / 50; j++) {
irons.add(new Iron(j * 50, i * 50));
p.repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
while (true) {
p.repaint();
Thread.sleep(1000);
} catch (InterruptedException e) {
f.addKeyListener(this);
private void drawOver(Graphics g) {
p.repaint();
g.setColor(Color.red);
g.setFont(new Font("Arial", 1, 100));
g.drawString("GAME OVER", 100, 200);
g.setFont(new Font("Arial", 2, 50));
g.drawString("Congratulation!
You Win!", 100, 400);
g.drawString("So Sorry,
You Lose!", 100, 400);
if (flash) {
g.setFont(new Font("Arial", 2, 30));
g.setColor(Color.BLACK);
g.drawString("Press F1 to try again...,", 150, 500);
g.drawString("Press the other Key to Return the Title...,", 150,
[代码运行效果截图][源代码打包下载](50积分)[1485 次下载]分享到:更多回复评论回复评论回复评论回复评论回复评论共71 条评论
发表评论:评论须知:1、评论每次加2分,每天上限为30;2、请文明用语,共同创建干净的技术交流环境;3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。& &&&java程序的运行过程和编译原理
java程序的运行过程和编译原理
如题所示,忘了这个了
悬赏20青鸟豆&|&浏览5131
才能回答问题
上面是运行过程,这是编译原理Java编译原理:&Java 虚拟机(JVM)是可运行Java 代码的假想计算机。只要根据JVM规格描述将解释器移植到特定的计算机上,就能保证经过编译的任何Java代码能够在该系统上运行。&  一.Java源文件的编译、下载 、解释和执行&  Java应用程序的开发周期包括编译、下载 、解释和执行几个部分。Java编译程序将Java源程序翻译为JVM可执行代码?字节码。这一编译过程同C/C++ 的编译有些不同。当C编译器编译生成一个对象的代码时,该代码是为在某一特定硬件平台运行而产生的。因此,在编译过程中,编译程序通过查表将所有对符号的引用转换为特定的内存偏移量,以保证程序运行。Java编译器却不将对变量和方法的引用编译为数值引用,也不确定程序执行过程中的内存布局,而是将这些符号引用信息保留在字节码中,由解释器在运行过程中创立内存布局,然后再通过查表来确定一个方法所在的地址。这样就有效的保证了Java的可移植性和安全 性。&  &  运行JVM字节码的工作是由解释器来完成的。解释执行过程分三部进行:代码的装入、代码的校验和代码的执行。装入代码的工作由&类装载器&(class loader)完成。类装载器负责装入运行一个程序需要的所有代码,这也包括程序代码中的类所继承的类和被其调用的类。当类装载器装入一个类时,该类被放在自己的名字空间中。除了通过符号引用自己名字空间以外的类,类之间没有其他办法可以影响其他类。在本台计算机上的所有类都在同一地址空间内,而所有从外部引进的类,都有一个自己独立的名字空间。这使得本地类通过共享相同的名字空间获得较高的运行效率,同时又保证它们与从外部引进的类不会相互影响。当装入了运行程序需要的所有类后,解释器便可确定整个可执行程序的内存布局。解释器为符号引用同特定的地址空间建立对应关系及查询表。通过在这一阶段确定代码的内存布局,Java很好地解决了由超类改变而使子类崩溃的问题,同时也防止了代码对地址的非法访问。&  &  随后,被装入的代码由字节码校验器进行检查。校验器可发现操作数栈溢出,非法数据类型转化等多种错误。通过校验后,代码便开始执行了。&  &  Java字节码的执行有两种方式:&  1.即时编译方式:解释器先将字节码编译成机器码,然后再执行该机器码。&  2.解释执行方式:解释器通过每次解释并执行一小段代码来完成Java字节码程 序的所有操作。&  通常采用的是第二种方法。由于JVM规格描述具有足够的灵活性,这使得将字节码翻译为机器代码的工作&  &  具有较高的效率。对于那些对运行速度要求较高的应用程序,解释器可将Java字节码即时编译为机器码,从而很好地保证了Java代码的可移植性和高性能。&
我们手工执行java程序是这样的:1 在记事本中或者是UE的文本编辑器中,写好源程序;2
使用javac命令把源程序编译成.class文件;
编译后的.class(类字节码)文件中会包含以下内容...
本周答题榜
本周回答18题
本周回答13题
本周回答5题
本周回答4题
本周回答4题
本周回答3题
本周回答3题
本周回答3题
Beijing Aptech Beida Jade Bird Information Technology Co.,Ltd北大青鸟IT教育 北京阿博泰克北大青鸟信息技术有限公司 版权所有
京ICP备号-3自学 Java 怎么入门? - 知乎10367被浏览1420979分享邀请回答2.0K82 条评论分享收藏感谢收起21230 条评论分享收藏感谢收起查看更多回答8 个回答被折叠()4014人阅读
算法学习(58)
java语言基础(68)
1、有这样一个Room类:
public class Room {
&* 房间名称
private String roomN
&* 房间面积
&* 房间价格
private BigD
&* 酒店的地址
&* 酒店的电话
private String phoneNumber
还有这样一个Person类:
public class Person {
现在我们需要用HashMap做一个以room为key,以person为value的缓存,以提供快速查询指定房间入住了哪些人?
请完成一个可以运行的演示。
public class Person {
public Person(String name, int age, int weight){
this.username =
this.age =
this.weight =
public boolean equals(Object obj) {
if(!(obj instanceof Person))
Person p = (Person)
return this.username.equals(p.username)&&
this.age == p.age&&
this.weight == p.
public class Room {
private String roomN
private BigD
private String phoneN
public Room(String roomName, int area, BigDecimal price, String address, String phoneNumber){
this.roomName = roomN
this.area =
this.price =
this.address =
this.phoneNumber = phoneN
public int hashCode(){
int result = roomName.hashCode();
result = 31*result +
result = 31*result + address.hashCode();
result = 31*result + phoneNumber.hashCode();
return Objects.hashCode(roomName, area, address, phoneNumber);
public boolean equals(Object obj) {
if(!(obj instanceof Room))
Room tmpRoom = (Room)
return this.address.equals(tmpRoom.address)&&
this.phoneNumber.equals(tmpRoom.phoneNumber)&&
this.roomName.equals(tmpRoom.roomName)&&
this.area==tmpRoom.
public class RoomCache {
HashMap&Room, Person&
public RoomCache(){
cache = new HashMap&Room, Person&();
public void put(Room room, Person person){
cache.put(room, person);
public Person get(Room room){
return cache.get(room);
2、根据指定项目目录下(可以认为是java源文件目录)中,统计被import最多的类。
public class MostImportClass {
String dirN
HashMap&String, Integer& importClassR
public MostImportClass(String dir){
this.dirName =
importClassRecords = new HashMap&String, Integer&();
this.statisticsClazz(new File(this.dirName));
public int get(String clazzName){
Integer value = importClassRecords.get(clazzName);
if(value==null) return 0;
public void processFile(File file){
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String line =
while((line = reader.readLine()) != null){
line = line.trim();
if(line.startsWith(&public&)||line.startsWith(&class&)){
if(line.startsWith(&import&)){
String className = line.substring(6, line.length()-1).trim();
Integer value = importClassRecords.get(className);
if(value==null){
importClassRecords.put(className, 1);
importClassRecords.put(className, value+1);
} catch (IOException e) {
e.printStackTrace();
public void statisticsClazz(File file){
if(!file.isDirectory()){
processFile(file);
File [] files = file.listFiles();
for(File tmpFile: files){
statisticsClazz(tmpFile);
public String getMostImportClazzName(){
int max = Integer.MIN_VALUE;
String clazzName =
for(Entry item: this.importClassRecords.entrySet()){
String key = (String) item.getKey();
int value = (Integer)item.getValue();
if(value&max){
clazzName =
return clazzN
1) 查找一个目录下,所有文件中数字、字母(大小写不区分)、汉字、空格的个数、行数。
2) 将结果数据写入到文件中。
文件格式如下:
数字:198213个
字母:18231个
汉字:1238123个
空格:823145个
行数:99812行
数字0:123个
数字1:1214个
数字2:23423个
字母A:754456个
数字B:7567个
数字C:456456个
class Item{
public Item(int x){
public String toString(){
return this.x+&&;
* @author Cool
*/public class GuavaTest implements Comparable&GuavaTest&{
public GuavaTest(int x, int y){
public String toString(){
String ss = MoreObjects.toStringHelper(&GuavaTest&)
.add(&x&, 12)
.add(&b&, false)
.toString();
public int compareTo(GuavaTest o) {
return ComparisonChain.start()
.compare(this.x, o.x)
.compare(this.y, o.y)
.result();
public static void countChinese(){
String str = new String(&abc中国cd你好啊89&);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
System.out.println(&length = &+str.length());
System.out.println(&bytes length = &+str.getBytes().length);
for (int i = 0; i & str.length(); i++)
temp = String.valueOf(str.charAt(i));
if (temp.matches(E1))
chineseCount++;
if (temp.matches(E2))
englishCount++;
if (temp.matches(E3))
numberCount++;
System.out.println(&汉字数:& + chineseCount);
System.out.println(&英文数:& + englishCount);
System.out.println(&数字数:& + numberCount);
System.out.println(&特殊字符:& + (str.length() - (chineseCount + englishCount + numberCount)));
public static void countFile(String filename) throws IOException{
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
String E4 = & &;
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
int spaceCount = 0;
int lineCount = 0;
TreeMultiset&String& chineseWordsCount = TreeMultiset.create(),
englishWordsCount = TreeMultiset.create(),
numberWordsCount = TreeMultiset.create();
for(String line : lines){
lineCount ++;
line = line.toLowerCase();
for(int i=0; i&line.length(); i++){
String word = String.valueOf(line.charAt(i));
if(word.matches(E1)){
chineseCount++;
chineseWordsCount.add(word);
}else if(word.matches(E2)){
englishCount++;
englishWordsCount.add(word);
}else if(word.matches(E3)){
numberCount++;
numberWordsCount.add(word);
}else if(word.matches(E4)){
spaceCount++;
System.out.println(&数字:&+numberCount+&个&);
System.out.println(&字母:&+englishCount+&个&);
System.out.println(&汉字:&+chineseCount+&个&);
System.out.println(&空格:&+spaceCount+&个&);
System.out.println(&行数:&+lineCount+&行\n&);
for(String word: numberWordsCount.elementSet()){
System.out.println(&数字&+word+&:&+numberWordsCount.count(word)+&个&);
for(String word: englishWordsCount.elementSet()){
System.out.println(&字母&+word+&:&+englishWordsCount.count(word)+&个&);
for(String word: chineseWordsCount.elementSet()){
System.out.println(&汉字&+word+&:&+chineseWordsCount.count(word)+&个&);
public static void countCodeLines(String filename) throws IOException{
int linesCount = 0;
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
boolean incomment =
String tab = &\\s+&;
for(String line : lines){
line = line.trim();
if(line.startsWith(&//&)||line.equals(&&))
if(!incomment&&!line.startsWith(&/*&)){
linesCount ++ ;
if(line.contains(&/*&)){
incomment =
if(incomment&&line.contains(&*/&)){
incomment =
line = line.substring(line.indexOf(&*/&)+2).trim();
if(line!=&&&&!line.startsWith(&//&)){
linesCount ++;
System.out.println(linesCount);
public static void main(String [] args) throws IOException{
countFile(&./src/main/java/MyTest/MyTest/myguava/GuavaTest.java&);
countCodeLines(&./src/main/java/MyTest/MyTest/myguava/TestClass.java&);
int count = 0;
System.out.println(!true&&(count++ == 0));
String line = &8&;
System.out.println(line.substring(8));
String s =/**
Optional&String& possible = Optional.fromNullable(s);
System.out.println(possible.isPresent());
Preconditions.checkNotNull(s, &s is null&);
System.out.println(new GuavaTest(1, 1));
GuavaTest g = new GuavaTest(1, 1), g2 = new GuavaTest(1, 2);
System.out.pareTo(g2));
Ordering&Item& order = Ordering.natural().onResultOf(new Function&Item, Integer&(){
public Integer apply(Item input) {
return input.x;
List&Item& list = new ArrayList&Item&();
list.add(new Item(9));
list.add(new Item(2));
list.add(new Item(10));
List&Item& tmp = order.sortedCopy(list);
System.out.println(tmp);
ImmutableSet&String& set = ImmutableSet.of(&a&, &b&, &c&);
for(String s: set){
System.out.println(&+&+s);
Multiset&String& mset = HashMultiset.create();
mset.add(&a&);
mset.add(&b&);
mset.add(&c&);
mset.add(&a&);
for(String s: mset){
System.out.println(&+&+s);
System.out.println(mset.count(&a&));
BiMap&String, Integer& userId = HashBiMap.create();
userId.put(&a&, 1);
userId.put(&a&, 2);
userId.put(&b&, 3);
System.out.println(userId.get(&a&));
System.out.println(userId.inverse().get(1));
4、统计附件中的StringUtils.java文件的有效代码行数。&
1) 有效不包括空行、注释
2) 考虑代码里有多行注释的情况
class Item{
public Item(int x){
public String toString(){
return this.x+&&;
* @author Cool
*/public class GuavaTest implements Comparable&GuavaTest&{
public GuavaTest(int x, int y){
public String toString(){
String ss = MoreObjects.toStringHelper(&GuavaTest&)
.add(&x&, 12)
.add(&b&, false)
.toString();
public int compareTo(GuavaTest o) {
return ComparisonChain.start()
.compare(this.x, o.x)
.compare(this.y, o.y)
.result();
public static void countChinese(){
String str = new String(&abc中国cd你好啊89&);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
System.out.println(&length = &+str.length());
System.out.println(&bytes length = &+str.getBytes().length);
for (int i = 0; i & str.length(); i++)
temp = String.valueOf(str.charAt(i));
if (temp.matches(E1))
chineseCount++;
if (temp.matches(E2))
englishCount++;
if (temp.matches(E3))
numberCount++;
System.out.println(&汉字数:& + chineseCount);
System.out.println(&英文数:& + englishCount);
System.out.println(&数字数:& + numberCount);
System.out.println(&特殊字符:& + (str.length() - (chineseCount + englishCount + numberCount)));
public static void countFile(String filename) throws IOException{
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
String E4 = & &;
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
int spaceCount = 0;
int lineCount = 0;
TreeMultiset&String& chineseWordsCount = TreeMultiset.create(),
englishWordsCount = TreeMultiset.create(),
numberWordsCount = TreeMultiset.create();
for(String line : lines){
lineCount ++;
line = line.toLowerCase();
for(int i=0; i&line.length(); i++){
String word = String.valueOf(line.charAt(i));
if(word.matches(E1)){
chineseCount++;
chineseWordsCount.add(word);
}else if(word.matches(E2)){
englishCount++;
englishWordsCount.add(word);
}else if(word.matches(E3)){
numberCount++;
numberWordsCount.add(word);
}else if(word.matches(E4)){
spaceCount++;
System.out.println(&数字:&+numberCount+&个&);
System.out.println(&字母:&+englishCount+&个&);
System.out.println(&汉字:&+chineseCount+&个&);
System.out.println(&空格:&+spaceCount+&个&);
System.out.println(&行数:&+lineCount+&行\n&);
for(String word: numberWordsCount.elementSet()){
System.out.println(&数字&+word+&:&+numberWordsCount.count(word)+&个&);
for(String word: englishWordsCount.elementSet()){
System.out.println(&字母&+word+&:&+englishWordsCount.count(word)+&个&);
for(String word: chineseWordsCount.elementSet()){
System.out.println(&汉字&+word+&:&+chineseWordsCount.count(word)+&个&);
public static void countCodeLines(String filename) throws IOException{
int linesCount = 0;
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
boolean incomment =
String tab = &\\s+&;
for(String line : lines){
line = line.trim();
if(line.startsWith(&//&)||line.equals(&&))
if(!incomment&&!line.startsWith(&/*&)){
linesCount ++ ;
if(line.contains(&/*&)){
incomment =
if(incomment&&line.contains(&*/&)){
incomment =
line = line.substring(line.indexOf(&*/&)+2).trim();
if(line!=&&&&!line.startsWith(&//&)){
linesCount ++;
System.out.println(linesCount);
public static void main(String [] args) throws IOException{
countFile(&./src/main/java/MyTest/MyTest/myguava/GuavaTest.java&);
countCodeLines(&./src/main/java/MyTest/MyTest/myguava/TestClass.java&);
int count = 0;
System.out.println(!true&&(count++ == 0));
String line = &8&;
System.out.println(line.substring(8));
String s =/**
Optional&String& possible = Optional.fromNullable(s);
System.out.println(possible.isPresent());
Preconditions.checkNotNull(s, &s is null&);
System.out.println(new GuavaTest(1, 1));
GuavaTest g = new GuavaTest(1, 1), g2 = new GuavaTest(1, 2);
System.out.pareTo(g2));
Ordering&Item& order = Ordering.natural().onResultOf(new Function&Item, Integer&(){
public Integer apply(Item input) {
return input.x;
List&Item& list = new ArrayList&Item&();
list.add(new Item(9));
list.add(new Item(2));
list.add(new Item(10));
List&Item& tmp = order.sortedCopy(list);
System.out.println(tmp);
ImmutableSet&String& set = ImmutableSet.of(&a&, &b&, &c&);
for(String s: set){
System.out.println(&+&+s);
Multiset&String& mset = HashMultiset.create();
mset.add(&a&);
mset.add(&b&);
mset.add(&c&);
mset.add(&a&);
for(String s: mset){
System.out.println(&+&+s);
System.out.println(mset.count(&a&));
BiMap&String, Integer& userId = HashBiMap.create();
userId.put(&a&, 1);
userId.put(&a&, 2);
userId.put(&b&, 3);
System.out.println(userId.get(&a&));
System.out.println(userId.inverse().get(1));
5、文件替换:
写一个程序, 读入 template.txt 和 env.properties
将template 中 ${NAME}表达式里的变量替换为env里设定的值. 然后输出到一个文件里.
第一个变量是: ${webwork.jsp.include_flush}
第二个变量是: ${webwork.i18n.encoding}
第三个第四个变量分别是: ${webwork.ui.templateSuffix}和${webwork.ui.notfound}
public class TemplateReplaceTest {
public static void replace() throws IOException{
String template = &./source/template.txt&, env = &./source/env.properties&, output = &./source/output.txt&;
File templateFile = new File(template);
List&String& lines = Files.readLines(templateFile, Charsets.UTF_8);
Properties prop = new Properties();
FileInputStream in = new FileInputStream(new File(env));
prop.load(in);
in.close();
StringBuffer buffer = new StringBuffer();
for(String line: lines){
line = line.trim();
String name = line.substring(2, line.length()-1).trim();
buffer.append(&${&);
buffer.append(prop.getProperty(name, &&));
buffer.append(&}\n&);
Files.write(buffer.toString().getBytes(), new File(output));
public static void main(String [] args) throws IOException{
String s = &0123456&;
System.out.println(s.substring(2, s.length()-1));
replace();
6、神雕文件替换:
/svn/fresh/javabase/branches/java-base-1/src/main/resources/
写一个程序,读入 sdxl.txt 和 env.properties,
将sdxl.txt中 ${NAME}表达式里的变量替换为env里设定的值,然后输出到一个文件里.
7、神雕文件替换:
现有2个文件,地址在:
1) /sites/task3.txt
2) /sites/task3_prop.txt
根据task3_prop.txt中内容替换掉task3.txt 里$function(index)形式文字,将其还原成一本完整小说。
其中function有4种函数,替换规则如下:
1) natureOrder 自然排序,即文本中排列顺序
2) indexOrder 索引排序,文本中每行第一个数字为索引
3) charOrder 文本排序,java的字符排序
4) charOrderDESC 文本倒序,java的字符倒序
注意:txt文件需要程序中现读现解析,而不是下载成本地文件。
最终转换过来的文件大小是:。
public class ShendiaoReplace {
private static final String task3Url = &/sites/task3.txt&;
private static final String taskPropUrl = &/sites/task3_prop.txt&;
private static final String output = &./source/output.txt&;
private LinkedList&String& keyList = Lists.newLinkedList();
private HashMap&String, String& keyMap = Maps.newHashMap();
public static List&String& readContext(String url) throws IOException{
URL myUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)myUrl.openConnection();
conn.setDoInput(true);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
List&String& list = Lists.newLinkedList();
String s =
while((s=br.readLine())!=null){
list.add(s);
public void processTask3Prop() throws IOException{
List&String& list = readContext(taskPropUrl);
for(String line: list){
line = line.trim();
if(line.equals(&&))
System.out.println(line);
Iterable&String& items = Splitter.on(& &)
.omitEmptyStrings()
.split(line);
System.out.println(items);
Iterator&String& i = items.iterator();
String index = i.next(), words = i.next();
keyList.add(words);
keyMap.put(index, words);
public static class FunctionDesc{
int start,
String functionN
public FunctionDesc(int s, int e, String name, String index){
this.start =
this.end =
this.functionName =
this.index =
public String toString(){
return &[start = &+start+&, end = &+end+&, functionName = &+functionName + &, index = &+index+&]&;
public List&FunctionDesc& processTask3Line(String line){
List&FunctionDesc& funtionList = Lists.newArrayList();
int index = -1, prev = -1;
while((index = line.indexOf(&$&, prev+1))!=-1){
int tmpEnd = line.indexOf(&(&, index);
String name = line.substring(index+1, tmpEnd);
int end = line.indexOf(&)&, tmpEnd);
String indexS = line.substring(tmpEnd+1, end);
funtionList.add(new FunctionDesc(index, end, name, indexS));
return funtionL
public String function(String functionName, String indexName, int i){
boolean desc =
if(functionName.equals(&natureOrder&)){
return keyList.get(i);
}else if(functionName.equals(&indexOrder&)){
return keyMap.get(indexName);
}else if(functionName.equals(&charOrderDESC&)){
String [] items = keyList.get(i).split(&&);
Arrays.sort(items);
Arrays.sort(items, new Comparator&String&(){
public int compare(String o1, String o2) {
return -o1.compareTo(o2);
StringBuffer buffer = new StringBuffer();
for(String item: items){
buffer.append(item);
return buffer.toString();
public void replaceShendiao() throws IOException{
this.processTask3Prop();
List&String& taskLines = readContext(task3Url);
StringBuffer buffer = new StringBuffer();
int index = 0;
for(String line : taskLines){
line = line.trim();
if(line.equals(&&)) {
buffer.append(&\n&);
List&FunctionDesc& items = this.processTask3Line(line);
int last = 0;
StringBuffer tmpLine = new StringBuffer();
int prev = -1;
for(FunctionDesc fun: items){
tmpLine.append(line.substring(prev+1, fun.start));
tmpLine.append(function(fun.functionName, fun.index, index++));
prev = fun.
last = fun.
tmpLine.append(line.substring(last+1));
tmpLine.append(&\n&);
buffer.append(tmpLine);
String context = buffer.toString();
System.out.println(&最终转换过来的文件大小是:&+context.length());
Files.write(context.getBytes(), new File(output));
public static void main(String [] args) throws IOException{
System.out.println(readContext(&/sites/task3.txt&));
ShendiaoReplace shen = new ShendiaoReplace();
shen.processTask3Prop();
System.out.println(shen.keyList);
System.out.println(shen.keyMap);
String line = &当下手臂一缩一圈,使出母亲所授的小$natureOrder(72)夫,手掌打当下手臂一缩一圈,使出母亲所授的小$naturefasdOrder(72)夫,手掌打&;
System.out.println(line);
System.out.println(shen.processTask3Line(line));
shen.replaceShendiao();
System.out.println(line.indexOf(&$&));
1、输入年份,如2014,打印出该年万年历,以及标识出当天日期。类似于linux下的cal -y结果。
public class Calendar {
public static boolean isLeapYear(int year){
boolean leapYear =
if(year%100==0&&year%400==0){
leapYear =
}else if(year%100!=0&&year%4==0){
leapYear =
return leapY
* 以日,周四,为基准
* @param year
public static int countDays(int year){
int days = 0;
int start = 2015;
if(start&end){
end = 2015;
for(int i= i& i++){
if(isLeapYear(i)){
days += 366;
days +=365;
public static void showCalendar(int year){
int days = countDays(year);
int weekDay = days%7;
if(year&=2015){
weekDay = (weekDay+4)%7;
weekDay = 4 - weekD
if(weekDay&0){
weekDay += 7;
String [] monthLabels = new String[]{&January&, &February&, &March&, &April&, &May&, &June&, &July&, &August&, &September&, &October&, &November&, &December&};
String [] labels = new String[]{&Su&, &Mo&, &Tu&, &We&, &Th&, &Fr&, &Sa&};
for(int i=1; i&=12; i++){
System.out.println(&\n\n&+monthLabels[i-1]);
for(String label: labels){
System.out.print(label+& &);
System.out.println();
int monthDays = 30;
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12){
monthDays = 31;
}else if(i==2){
if(isLeapYear(year)){
monthDays = 29;
}else monthDays = 28;
for(int j=0; j&weekD j++){
System.out.print(&
for(int j=1; j&=monthD j++){
if((j+weekDay-1)%7==0) System.out.println();
System.out.print(j+& &);
weekDay = (weekDay+monthDays) % 7;
public static void main(String [] args){
showCalendar(2013);
public class Calendar
public static boolean isLeapYear(int year){
boolean leapYear =
if(year%100==0&&year%400==0){
leapYear =
}else if(year%100!=0&&year%4==0){
leapYear =
return leapY
* 以日,周四,为基准
* @param year
public static int countDays(int year){
int days = 0;
int start = 2015;
if(start&end){
end = 2015;
for(int i= i& i++){
if(isLeapYear(i)){
days += 366;
days +=365;
public static void showCalendar(int year){
int days = countDays(year);
int weekDay = days%7;
if(year&=2015){
weekDay = (weekDay+4)%7;
weekDay = 4 - weekD
if(weekDay&0){
weekDay += 7;
String [] monthLabels = new String[]{&January&, &February&, &March&, &April&, &May&, &June&, &July&, &August&, &September&, &October&, &November&, &December&};
String [] labels = new String[]{&Su&, &Mo&, &Tu&, &We&, &Th&, &Fr&, &Sa&};
List&StringBuffer& lines =
for(int l=1; l&=4; l++){
lines = new LinkedList&StringBuffer&();
int s = (l-1)*3 + 1, e = l*3;
for(int i=s; i&=e; i++){
int lineCount = 0, size = lines.size();
StringBuffer tmpLine =
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
tmpLine = lines.get(lineCount);
tmpLine.append(&\t\t&);
tmpLine.append(monthLabels[i-1]+&\t\t\t\t\t\t&);
lineCount = 1;
size = lines.size();
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
tmpLine = lines.get(lineCount);
tmpLine.append(&\t\t&);
for(String label: labels){
tmpLine.append(label + &\t&);
int monthDays = 30;
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12){
monthDays = 31;
}else if(i==2){
if(isLeapYear(year)){
monthDays = 29;
}else monthDays = 28;
boolean firstLoop =
for(int j=1; j&=monthD j++){
if((j+weekDay-1)%7==0||firstLoop){
lineCount ++;
size = lines.size();
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
int emptyMonths = i -
for(int em=0; em&emptyM em++){
tmpLine.append(&\t\t\t\t\t\t\t\t\t&);
tmpLine = lines.get(lineCount);
tmpLine.append(&\t\t&);
if(firstLoop){
for(int fi=0; fi&weekD fi++){
tmpLine.append(&\t&);
firstLoop =
tmpLine.append(j+&\t&);
int restDays = 35-monthDays-weekD
if(restDays&0){
if(restDays&=7){
lineCount ++;
size = lines.size();
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
int emptyMonths = i -
for(int em=0; em&emptyM em++){
tmpLine.append(&\t\t\t\t\t\t\t&);
tmpLine = lines.get(lineCount);
if(restDays&=7){
tmpLine.append(&\t\t&);
for(int j=0; j&(35-monthDays-weekDay); j++){
tmpLine.append(&\t&);
weekDay = (weekDay+monthDays) % 7;
for(StringBuffer sbline: lines){
System.out.println(sbline);
System.out.println();
public static void main(String [] args){
showCalendar(2015);
2、文件统计:&1) 按照附件第一列分组,输出类似于a -&c f(有去重)2) 统计每个字母出现的次数附件内容:b a ca c fb f ac d ea c cd e f
public class Count {
private final static String input = &./source/task2.txt&;
public static void count() throws IOException{
List&String& lines = Files.readLines(new File(input), Charsets.UTF_8);
Multimap&Character, Character& maps = HashMultimap.create();
for(String line: lines){
line = line.trim();
if(line.equals(&&))
Iterable&String& chars = Splitter.on(& &).split(line);
Iterator&String& iter = chars.iterator();
Character key = iter.next().charAt(0),
v1 = iter.next().charAt(0),
v2 = iter.next().charAt(0);
maps.put(key, v1);
maps.put(key, v2);
for(Character key: maps.keySet()){
System.out.print(key+& -& &);
Iterable&Character& values = maps.get(key);
Ordering&Character& order = Ordering.natural();
List&Character& list = order.sortedCopy(values);
for(Character v: list){
System.out.print(v+& &);
System.out.println();
public static void main(String [] args) throws IOException{
3、jvm提供了一个jstack的工具,可以把该jvm中运行的线程堆栈导出,具体见j.stack文件&
&DubboServerHandler-192.168.6.96:20880-thread-143& daemon prio=10 tid=0x6d000 nid=0x1807 waiting on condition [0xcfa000]
&java.lang.Thread.State: WAITING (parking)
&at sun.misc.Unsafe.park(Native Method)
&- parking to wait for &0xc16b630& (a java.util.concurrent.SynchronousQueue$TransferStack)
&at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
&at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:422)
&at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:323)
&at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:857)
&at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
&at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
&at java.lang.Thread.run(Thread.java:619)
DubboServerHandler-192.168.6.96:20880-thread-143为线程的名字,tid为线程id ,java.lang.Thread.State: WAITING,WAITING为线程状态
waiting on condition [0xcfa000]表示该线程waiting在tid=0xcfa000的线程上
请写一个程序,解析出线程名,线程id,线程状态,以及哪些线程wait在同一个condition上 。就是说匹配“waiting on condition”的线程进行统计。
输出结果按照等待同一个condition的线程数从大到小排序。
输出格式如下:
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
线程id|线程名|线程状态
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
j.stack在:
/pages/viewpageattachments.action?pageId=5570576&metadataLink=true
public class CountJStack {
static class ThreadItem{
String threadN
public ThreadItem(String name, String id, String state, String condition){
this.threadName =
this.tid =
this.state =
this.condition =
public boolean equals(Object obj) {
if(!(obj instanceof ThreadItem))
ThreadItem item = (ThreadItem)
return this.tid.equals(item.tid);
public String toString(){
//线程id|线程名|线程状态
return &线程& + this.tid + &|&+this.threadName+&|&+
static class CounterLine implements LineProcessor&Multimap&String, ThreadItem&& {
private static final String stateString = &java.lang.Thread.State:&;
Multimap&String, ThreadItem& maps = HashMultimap.create();
boolean inblock =
StringBuffer buffer = new StringBuffer();
public void processBlock(String block){
int s = block.indexOf(&\&&), e = block.indexOf(&\&&, s+1);
String name = block.substring(s+1, e);
s = block.indexOf(&tid=&);
e = block.indexOf(& &, s);
String tid = block.substring(s+4, e);
s = block.indexOf(&[&);
e = block.indexOf(&]&, s);
String condition = block.substring(s+1, e).trim();
s = block.indexOf(stateString);
e = block.indexOf(&\n&, s);
String state = block.substring(s+stateString.length(), e);
ThreadItem item = new ThreadItem(name, tid, state, condition);
maps.put(condition, item);
}catch(Exception e){
//do nothing
public boolean processLine(String line) throws IOException {
line = line.trim();
if(inblock&&(line.equals(&&)||line.startsWith(&\&&))){
this.processBlock(buffer.toString());
buffer.delete(0, buffer.length());
if(line.startsWith(&\&&)){
buffer.append(line);
buffer.append(&\n&);
if(!inblock&&!line.startsWith(&\&&))
if(!inblock&&line.startsWith(&\&&)){
if(inblock){
buffer.append(line);
buffer.append(&\n&);
public Multimap&String, ThreadItem& getResult() {
public static void main(String[] args) throws IOException {
String testFilePath = &./source/j.stack&;
File testFile = new File(testFilePath);
CounterLine counter = new CounterLine();
Files.readLines(testFile, Charsets.UTF_8, counter);
Multimap&String, ThreadItem& maps = counter.getResult();
for(String condition: maps.keySet()){
Iterable&ThreadItem& iters = maps.get(condition);
List&ThreadItem& list = Lists.newArrayList(iters);
System.out.println(&condition &+condition+&, &+list.size()+&:&);
for(ThreadItem item: list){
System.out.println(item);
4、输入:给定一个hotelinfo文件,文件格式如下:&
shanghai_city_7208 上海全季酒店淮海路店
shanghai_city_14744 锦江之星上海金山城市沙滩店
jinan_2794 章丘市大众旅馆
carmel_ca_5 Carmel River Inn
格式说明:
1)一共两列,之间使用tab分隔
2)第一列是酒店代号,第二列是酒店名称
3)以shanghai_city_7208为例,前面的shanghai_city代表城市
要求如下:
1. 输出一个文件,和hotelinfo格式一样,但是按照酒店代号进行降序排序
2. 输出一个文件,两列,第一列是城市代号,第二列是这个城市下的酒店数,但是按照酒店数进行降序排序
hotelinfo文件在:/download/attachments/4850688/hotelinfo.txt?version=2&modificationDate=0&api=v2
public class HotelInfo {
private static final String input = &./source/hotelinfo&,
output1 = &./source/hotel1.txt&,
output2 = &./source/hotel2.txt&;
@SuppressWarnings(&unchecked&)
public static void processHotel(){
TreeMap&String, String& maps = Maps.newTreeMap();
Multiset&String& sets = HashMultiset.create();
FileInputStream inputStream =
Scanner sc =
inputStream = new FileInputStream(input);
sc = new Scanner(inputStream, &UTF-8&);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String [] items = line.split(&\t&);
maps.put(items[0], items[1]);
int e = items[0].lastIndexOf(&_&);
sets.add(items[0].substring(0, e));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Set&String& keys = maps.descendingKeySet();
StringBuffer buffer = new StringBuffer();
for(String key: keys){
buffer.append(key);
buffer.append(&\t&);
buffer.append(maps.get(key)+&\n&);
Files.write(buffer.toString().getBytes(), new File(output1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
HashMap&String, Integer& tmpMap = Maps.newHashMap();
for(String key: sets.elementSet()){
tmpMap.put(key, sets.count(key));
List&Map.Entry&String, Integer&& list = new LinkedList&Map.Entry&String, Integer&&(tmpMap.entrySet());
Collections.sort(list, new Comparator() {
//将链表按照值得从大到小进行排序
public int compare(Object o1, Object o2) {
Map.Entry&String, Integer& e1 = (Map.Entry&String, Integer&)o1,
e2 = (Map.Entry&String, Integer&)o2;
return -e1.getValue().compareTo(e2.getValue());
buffer.delete(0, buffer.length());
for(Map.Entry&String, Integer& entry: list){
buffer.append(entry.getKey());
buffer.append(&\t&);
buffer.append(entry.getValue());
buffer.append(&\n&);
Files.write(buffer.toString().getBytes(), new File(output2));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public static void main(String[] args) throws IOException {
processHotel();
5、以下格式 ~ 100表示入住,离店,入住一天的价格是¥100。&
现有文件中包含多行这样的日期价格段,请将其合并,合并的规则包括:
1)价格相同,日期段相邻或者重叠的需要合并
2)相同日期的价格已后面录入的为准
合并后就是
合并之后就是
请读入指定文件price.txt和data.txt,并将所有的日期价格段合并后,按照入住日期升序展示,输出到控制台即可。
public class DateMerge {
private final static String pricefile = &./source/price.txt&;
public static void processPrice() throws IOException, ParseException{
List&String& lines = Files.readLines(new File(pricefile), Charsets.UTF_8);
RangeMap&Date, Integer& rangeMap = TreeRangeMap.create();
SimpleDateFormat format = new SimpleDateFormat(&yyyy-MM-dd&);
for(String line: lines){
line = line.trim();
if(line.equals(&&))
String [] items = line.split(& &);
String [] dates = items[0].split(&~&);
Date s = format.parse(dates[0]),
e = format.parse(dates[1]);
Date bs = new Date(s.getTime()-24*),
ae = new Date(e.getTime()+24*);
int value = Integer.parseInt(items[1]);
Entry&Range&Date&, Integer& entryS = rangeMap.getEntry(bs),
entryE = rangeMap.getEntry(ae);
if(entryS!=null&&entryS.getValue().equals(value)){
rangeMap.remove(entryS.getKey());
s = entryS.getKey().lowerEndpoint();
if(entryE!=null&&entryE.getValue().equals(value)){
rangeMap.remove(entryE.getKey());
e = entryE.getKey().upperEndpoint();
rangeMap.put(Range.closed(s, e), value);
Map&Range&Date&, Integer& rangeDateMap = rangeMap.asMapOfRanges();
Set&Entry&Range&Date&, Integer&& entries = rangeDateMap.entrySet();
Iterator&Entry&Range&Date&, Integer&& iterator = entries.iterator();
while(iterator.hasNext()){
Entry&Range&Date&, Integer& next = iterator.next();
System.out.println(next.getKey() + &\t& + next.getValue());
public static void main(String [] args) throws IOException, ParseException{
processPrice();
&/pre&&pre code_snippet_id=&682832& snippet_file_name=&blog__3897997& name=&code& class=&java&&6、假设我们有一个类HotelCenter,它有方法List&Hotel& getHotelList(String city)可以获得一个城市下所有酒店列表,
Hotel类有如下属性String name, String address, int price, Map&String, String& properties
酒店的非name和address的属性都可以通过properties.get(key)得到
我们需要实现以下功能
根据页面传入的参数返回对应的酒店列表,参数键值对会以&分割,参数的值如果有多个,会有逗号分隔
下述任何参数都可能缺失,对应的值如果为空串,也当做该参数不存在处理
参数会分三部分组成,过滤参数、排序参数和翻页参数
过滤参数包括
city(酒店所在城市)
name(酒店名包括name的值)
address(酒店地址包括address的值)
brand(酒店品牌属于brand的值的一个)
star(酒店星级属于star的值中的一个)
price(酒店价格在price值区间范围内)
area(酒店所属区域等于area值中的一个)
排序参数包括
sort(按照sort的值进行排序,如果值是price,就按照价格进行排序,如果值是star,则按照星级进行排序)
order(值如果是asc就是升序,是desc就是降序)
排序参数缺失时,默认按照sort=price&order=asc处理
翻页参数包括
page(page的值是需要看的酒店其实索引值和终止索引值,是左闭右开,如果选择的索引没有数据,则不处理,比如一共有30个酒店,page=20-40,需要返回后10个酒店)
翻页参数缺失时,默认按照0-20处理
以下是一个请求参数的例子
city=北京&name=酒店&address=海淀黄庄&brand=7天,如家&star=3,4&price=100-200,300-500&area=中关村&sort=price&order=desc&page=100-120
7、完成如下功能:
1)有一个(任意)对象,里面有N个properties以及getter和setter方法
2)有一个properties文件,有N个key,value来描述对象中property的值
3)有一个scheme固定的xml,用来描述这个对象
要求写一个解析器:
1)将xml中的占位符,替换为properties文件中的value
2) 将xml解析成对象,调用getter方法的时候可以获得值
3)用面向对象的思想,使该解析器有扩展性
例子见附件,注意:
1)对象是任意对象,不是例子中的Student,对象中的property都是java中的原生类型
2)xml和properties在使用的时候都是根据对象配置好的
3) xml的scheme是固定的,就是附件中的scheme
相关文件在:/pages/viewpage.action?pageId=7439502
public class Student {
public String getName() {
public void setName(String name) {
this.name =
public int getAge() {
public void setAge(int age) {
this.age =
public Date getBirth() {
public void setBirth(Date birth) {
this.birth =
public String toString(){
return &[ name = & + name +& , age = &+age+& , birth = & + birth+&]&;
}&/pre&&pre code_snippet_id=&682832& snippet_file_name=&blog__8663109& name=&code& class=&java&&&pre name=&code& class=&java&&public class RecoverObject&O& {
private String propertiesF
private String objectXmlF
private String recoverObjextXmlF
private String clazzN
public RecoverObject(String propertiesFile, String objectXmlFile){
this.propertiesFile = propertiesF
this.objectXmlFile = objectXmlF
this.recoverObjextXmlFile = this.objectXmlFile+&.recover&;
this.properties = new Properties();
initObject();
private void processXmlFile(String context){
int pre = -1, s = -1, e = -1;
StringBuffer buffer = new StringBuffer();
while((s = context.indexOf(&${&, pre+1))!=-1){
e = context.indexOf(&}&, s + 2);
buffer.append(context.substring(pre+1, s));
String attr = context.substring(s+2, e);
buffer.append(this.properties.get(attr));
buffer.append(context.substring(pre+1));
Files.write(buffer.toString().getBytes(), new File(this.recoverObjextXmlFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
private void initObject(){
FileInputS
in = new FileInputStream(new File(this.propertiesFile));
this.properties.load(in);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
StringBuffer buffer = new StringBuffer();
Scanner scan = new Scanner(new FileInputStream(new File(this.objectXmlFile)));
while(scan.hasNextLine()){
buffer.append(scan.nextLine());
buffer.append(&\n&);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String context = buffer.toString();
this.processXmlFile(context);
public O get(){
SAXBuilder builder=new SAXBuilder(false);
Class&?& demo=
Document doc=builder.build(this.recoverObjextXmlFile);
Element object=doc.getRootElement();
this.clazzName = object.getAttributeValue(&class&);
demo=Class.forName(this.clazzName);
O o = (O) demo.newInstance();
List propertiesList = object.getChildren(&property&);
for(Iterator iter = propertiesList.iterator(); iter.hasNext();){
Element attr = (Element) iter.next();
String attrName = attr.getAttributeValue(&name&);
String attrValue = attr.getChildText(&value&);
Field f= demo.getDeclaredField(attrName);
f.setAccessible(true);
Class&?& type = f.getType();
if(type.equals(String.class)){
f.set(o, attrValue);
}else if(type.equals(int.class)){
f.set(o, Integer.parseInt(attrValue));
}else if(type.equals(java.util.Date.class)){
SimpleDateFormat format = new SimpleDateFormat(&yyyy-MM-dd&);
f.set(o, format.parse(attrValue));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public static void main(String [] args){
RecoverObject&Student& object = new RecoverObject&Student&(&./source/object.properties2&, &./source/object.xml&);
Student s = object.get();
System.out.println(s);
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1640612次
积分:13359
积分:13359
排名:第967名
原创:187篇
转载:233篇
评论:114条
(4)(4)(11)(1)(1)(6)(3)(7)(2)(8)(27)(8)(7)(4)(11)(29)(19)(25)(9)(5)(5)(8)(8)(4)(4)(32)(17)(6)(3)(3)(25)(4)(8)(9)(9)(21)(12)(9)(3)(8)(4)(1)(18)(6)(2)}

我要回帖

更多关于 c语言程序代码 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信