《Head Frist Java》

2022年5月24日下午

Coding a Serious Business Application(编码较难的业务程序)

Classic children’s favorite, “99 bottles of beer.”
public class BeerSong {
 public static void main (String[] args) {
 int beerNum = 99;
 String word = “bottles”;
 while (beerNum > 0) {
 if (beerNum == 1) {
 word = “bottle”; // singular, as in ONE bottle.
 }
 System.out.println(beerNum + “ ” + word + “ of beer on the wall”);
 System.out.println(beerNum + “ ” + word + “ of beer.”);
 System.out.println(“Take one down.”);
 System.out.println(“Pass it around.”);
 beerNum = beerNum - 1;
 if (beerNum > 0) {
 System.out.println(beerNum + “ ” + word + “ of beer on the wall”);
 } else {
 System.out.println(“No more bottles of beer on the wall”);
 } // end else
 } // end while loop
 } // end main method
} // end class

这串代码最后循环出来是99*3条“bottles of beer on the wall”这算是简单的所谓“Serious Business Application”但是实际意义上的商业代码并不是这么简单的while/if的条件循环

 

Phrase-O-Matic(OMatic短语)
public class PhraseOMatic {
    public static void main (String[] args) {
        //make three sets of words to choose from.Add your own!

        String[] wordListOne = {"24/7","multi- Tier","30000 foot","B-to-B","win-win","front end", "web-based","pervasive",
                "smart", "six-sigma","critical-path", "dynamic"};
                
     String[] wordListTwo
= {"empowered", "sticky", "value-added", "oriented", "centric", "distributed", "clustered", "branded","outside-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"};
String[] wordListThree
= {"process", "tipping-point", "solution", "architecture", "core competency", "strategy", "mindshare", "portal", "space", "vision", "paradigm", "mission"}; // find out how many words are in each list int oneLength = wordListOne.length; int twoLength = wordListTwo.length; int threeLength = wordListThree.length; // generate three random numbers int rand1 = (int) (Math.random() * oneLength); int rand2 = (int) (Math.random() * twoLength); int rand3 = (int) (Math.random() * threeLength); // now build a phrase String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3]; // print out the phrase System.out.println("What we need is a " + phrase); } }

这串代码实现的是在三个单词列表中各自随机取出一个词,形成一段完整的句子。并print出来

然后我们花五步来完整解读这一段代码

1.创建三个包含所有单词的一个容器,也就是字符串数组

2.对于三个数组中的每一个,我们的目标是选择一个随机单词,要知道每个数组内有多少个单词(程序编译中第一个数的编号都是0)所以第14个单词的编号就是13

3.运用函数,在三个数组中随机调取出三个数(或者单词)且是介于0到数组总长度之间的一个数,而且需要强制为整数才能输出

4.构建这样一个短语,从三个数组中分别挑取三个词,将它们组成一个短语,并用空格隔开,再用“+”操作符将对象连接在一起。

5.最后输出出来

因为其随机性,我们每次输出的句子都会不一样。

 

 
 
 
 
 

posted on 2022-05-25 08:36  葉蓻蔿  阅读(35)  评论(0编辑  收藏  举报

导航