数组、包和API
一、数组
实例手把手,数组困难不再有。
36选7程序:从1-36中选取7个不重复的数据,组成一个有效的号码。如果该号码与特定号码相同,则中奖。
需求分析:
①一次能产生一注或多注号码
②每个号码的7为数字从小到大排序
③能打印输出对应的彩票,包括彩票头、号码等信息。
1、一维数组
请实现最简单的功能:一次打印一注号码
import java.io.*;
public class Lottery1 {
public static void main(String[] args) {
/*
* 一维数组的声明、创建和初始化。
*/
int[] lottery = new int[7]; //创建一个长度为7的整型数组
for (int i = 0; i < lottery.length; i++) { // 循环控制输出7列数字
lottery[i] = 1 + (int) (Math.random() * 36); // 产生一个1-36之间的随机整数
int j = 0; //声明一个变量并初始化为0,以便用来比较是否产生的随机数是否重复
while (j < i) { // 该循环用于避免重复号码的出现
if (lottery[i] == lottery[j]) { // 判断是否有重复号码出现
lottery[i] = 1 + (int) (Math.random() * 36); //若随机数重复,则重新产生
j = 0; //重置j,从0开始比较
} else
j++; //否则的话j自增
}
System.out.print(lottery[i] + "\t"); //输出数字的一个
}
System.out.println(); //数组全部输出完成后换行
}
}
2、二维数组
请实现稍微复杂的功能:一次打印多注号码
import java.util.Scanner;
public class Lottery2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //键盘输入语句
System.out.print("please input the num:"); //提示用户输入需要的注数
int num = sc.nextInt(); //将键盘输入的数赋给num
int[][] lottery = new int[num][7]; //定义一个num行和7列的二维数组
for (int i = 0; i < lottery.length; i++) { //外循环控制行数的输出(就是用户需要的注数)
for (int j = 0; j < lottery[i].length; j++) { //内循环用于产生一注号码(一注号码有7列)
lottery[i][j] = 1 + (int) (Math.random() * 36); //从1-36里边随机选数字
int k = 0; //定义一个变量k
while (k < j) { //用于从0开始检验是否随机产生的数字是否有重复
if (lottery[i][j] == lottery[i][k]) { //判断如果重复
lottery[i][j] = 1 + (int) (Math.random() * 36); //重新产生随机数字
k = 0; //从0开始重新检验是否有重复
} else //判断如果不重复
k++; //令k++,继续执行语句
}
}
}
/*二维数组的输出*/
for (int i = 0; i < lottery.length; i++) { //控制行输出
for (int j = 0; j < lottery[i].length; j++) { //控制列输出
System.out.print(lottery[i][j] + "\t"); //每隔一个table符便打印出一个数字
}
System.out.println(); //打印完一注号码后换行
}
}
}
3、数组与类的综合运用
请实现一个终极版的选票系统
import java.util.Arrays;
import java.util.Scanner;
public class Lottery { //以类的形式定义彩票
private int[][] lottery; //定义一个私有变量lottery
private String title = "36选7彩票卷"; //定义彩票头部的私有变量
private String strLabel = "****************************"; //定义一个美图修饰的私有变量
public void generateLottery(int num) { //定义一个输出注数的方法
lottery = new int[num][7];
for (int i = 0; i < lottery.length; i++) {
for (int j = 0; j < lottery[i].length; j++) {
lottery[i][j] = 1 + (int) (Math.random() * 36);
int k = 0;
while (k < j) {
if (lottery[i][j] == lottery[i][k]) {
lottery[i][j] = 1 + (int) (Math.random() * 36);
k = 0;
} else
k++;
}
}
Arrays.sort(lottery[i]); // 调用Arrays的方法进行数组的排序
}
}
public void printLottery() { //定义一个打印完整彩票的方法
/* 输出票头 */
System.out.println("\t" + title);
System.out.println(new java.util.Date());
System.out.println(strLabel);
/* 输出号码 */
for (int i = 0; i < lottery.length; i++) {
for (int j = 0; j < lottery[i].length; j++) {
System.out.print(lottery[i][j] + "\t");
}
System.out.println();
}
System.out.println(strLabel);
}
public static void main(String args[]) { //主方法进行测试
/*第一种直接运用Scanner键盘输入格式*/
/*
System.out.print("please input the num:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
Lottery lottery = new Lottery();
lottery.generateLottery(num);
lottery.printLottery();
*/
/*第二种直接运用命令行参数输入格式*/
if(args.length<1) {
System.out.println("请输入程序时以命令行形式输入号码注数");
return;
}
int num = Integer.parseInt(args[0]);
Lottery lottery = new Lottery();
lottery.generateLottery(num);
lottery.printLottery();
}
}
4、数组实战
请实现杨辉三角形的输出
import java.util.Scanner;
public class YanghuiTriangle {
public static void main(String[] args) {
/*解法一*/
/*
System.out.print("请输入杨辉三角形的行数:"); //系统提示输入三角形的行数
Scanner input = new Scanner(System.in); //创建键盘输入的对象input
int row = input.nextInt(); //将从键盘输入的值赋给row
int col = row; //令行与列相同
int[][] array = new int[row][col]; //定义一个二维数组
for (int i = 1; i < row; i++) { //控制杨辉三角形行数的输出
for (int j = row; j > i; j--) { // 控制打印之前输出的空格,使之成为一个等腰三角形
System.out.print(" "); //控制输出空格的个数
}
for (int j = 1; j <= i; j++) { //控制杨辉三角形列数的输出
if (i == j || j == 0) { //杨辉三角形的特点是:等腰的两条边的数字都是1
array[i][j] = 1; //即它们有以下的特点:array[i][0]=1或者array[i][j]=0
}
else { //杨辉三角形指定的一个值为(上一行的列数-1的元素)加上(上一行列数相同的元素)之和
array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
}
System.out.print(array[i][j] + " "); //打印二维数组的值并且输出空格
}
System.out.println();
}
*/
/*解法二*/
System.out.print("please input the row:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[][] array = new int[num][num]; //数组的声明与创建
for(int i=0;i<array.length;i++) {
for(int j=array.length;j>i;j--) {
System.out.print(" ");
}
for(int j=0;j<=i;j++) {
if(i==j||j==0) {
array[i][j]=1;
}
else {
array[i][j]=array[i-1][j-1]+array[i-1][j];
}
System.out.print(" "+array[i][j]+" ");
}
System.out.println();
}
}
}
4、字符串类的使用
(一)String类的使用
注意:String对象一经创建后其本身是不能修改的,所有的这些String类的修改方法实际是创建了一个新的字符串对象,并使对象变量指向该新创建的字符串对象。
字符串比较方法:
① boolean equals(Object anObject) 比较两个字符串是否相等,返回true或false。
② boolean equalsIgnoreCase(String anotherString) 比较两个字符串是否相等,忽略大小写。
③ int compareTo(String anotherString) 比较两个字符串的大小。若字符串比参数中的字符串大,则返回正整数;反之则返回负数;相等返回0.
① boolean equals(Object anObject) 比较两个字符串是否相等,返回true或false。
② boolean equalsIgnoreCase(String anotherString) 比较两个字符串是否相等,忽略大小写。
③ int compareTo(String anotherString) 比较两个字符串的大小。若字符串比参数中的字符串大,则返回正整数;反之则返回负数;相等返回0.
字符串的定位:
① int indexOf(char ch) 返回字符在串中首次出现的位置。若无此字符,则返回-1。
② int indexOf(int ch,int fromIndex) 返回从fromIndex处开始字符首次出现的位置,若无此字符,则返回-1。
③ int indexOf(String str) 返回字符串在串中首次出现的位置。若无此字符串,则返回-1。
④ int indexOf(String str,int fromIndex) 返回从fromIndex出开始字符串首次出现的位置,若无此字符串,则返回-1。
① int indexOf(char ch) 返回字符在串中首次出现的位置。若无此字符,则返回-1。
② int indexOf(int ch,int fromIndex) 返回从fromIndex处开始字符首次出现的位置,若无此字符,则返回-1。
③ int indexOf(String str) 返回字符串在串中首次出现的位置。若无此字符串,则返回-1。
④ int indexOf(String str,int fromIndex) 返回从fromIndex出开始字符串首次出现的位置,若无此字符串,则返回-1。
字符串的修改:
① String toLowerCase() 将字符串中的大写字母转变为小写字母。
② String toUpperCase() 将字符串中的小写字母转变为大写字母。
③ replace(char oldChar,char newChar) 将字符串中的oldChar字符用newChar字符替换。
④ String trim() 截取字符串两端的空白字符。
① String toLowerCase() 将字符串中的大写字母转变为小写字母。
② String toUpperCase() 将字符串中的小写字母转变为大写字母。
③ replace(char oldChar,char newChar) 将字符串中的oldChar字符用newChar字符替换。
④ String trim() 截取字符串两端的空白字符。
将其他数据类型转换为字符串的方法:
① static String valueOf(int i)
② static String valueOf(long i)
③ static String valueOf(float i)
④ static String valueOf(double i)
⑤ static String valueOf(char data[])
⑥ static String valueOf(char data[],int offset,int count)
⑦ static String valueOf(boolean b)
⑧ static String valueOf(char c)
① static String valueOf(int i)
② static String valueOf(long i)
③ static String valueOf(float i)
④ static String valueOf(double i)
⑤ static String valueOf(char data[])
⑥ static String valueOf(char data[],int offset,int count)
⑦ static String valueOf(boolean b)
⑧ static String valueOf(char c)
项目实战:
从键盘输入文本数据,并查找统计文本中出现的“java单词的个数
import java.util.Scanner;
public class StringDemo {
public static void main(String[] args) {
String word = new String("java"); //定义一个字符串并且赋值为"java"
Scanner in = new Scanner(System.in); //创建键盘输入对象in
String text = ""; //用于存放从键盘中输入的文本数据
String temptext = ""; //用于存放从文本中取出的字符串
int totalword = 0; //用于计算"Java"个数
System.out.println("please input the sentences:"); //提示输入语句
while(!(temptext=in.next()).equalsIgnoreCase("end")) { //控制循环条件
text += temptext;
}
/*下面代码用于求解text数据中包含的java单词数*/
int i = 0;
while(i<=text.length()-4) { //控制循环条件,i的值要大于或等于4才能进行循环
if(text.charAt(i)=='j'||text.charAt(i)=='J') { //判断字符是否为j
String subStr = text.substring(i, i+4); //将i到i+4的字符串赋给subStr
if(subStr.equalsIgnoreCase(word)) { //将字串与“java“进行比较
totalword++; //若相等,java个数+1
i=i+4; //将i往后移动4个
}
else i++; //若不是java字串,i后移一个字符
}
else i++; //若字符不为j,则i后移一个字符。
}
System.out.println("输入的文本共包含’Java‘单词"+totalword+"个");
}
}
(二)StringBuffer类的使用
注意:StringBuffer 对象是一种可变字符串对象,这种改变包括字符串长度和字符串内容的改变。StringBuffer类提供了对字符串的增删改查等操作方法。 StringBuffer对象的改变建立在原有对象的基础上,不会新创建一个对象,而String对象的改变都会引发新对象的创建。
构造器方法:
① StringBuffer() 用于创建空字符串对象,并为字符串分配好16个字符大小的缓存空间。
② StringBuffer(int len) 用于创建一个长度为len的字符串对象。
③ StringBuffer(String s) 创建一个初值为s的字符串对象,并再为字符串分配16个字符大小的缓存空间。
① StringBuffer() 用于创建空字符串对象,并为字符串分配好16个字符大小的缓存空间。
② StringBuffer(int len) 用于创建一个长度为len的字符串对象。
③ StringBuffer(String s) 创建一个初值为s的字符串对象,并再为字符串分配16个字符大小的缓存空间。
字符串修改方法:
① append(): 用于在字符串末尾添加各种数据,是一个重载方法。
② insert(int offset,int i): 用于在指定位置offset处插入各种数据,是一个重载方法。
③ delete(int start,int end):用于删除从start开始到(end-1)处的字符串。
④ reverse():用于对StringBuffer对象进行颠倒操作。
⑤ replace(int start,int end,String str):将方法的功能是将StringBuffer对象字符串中从start到end-1处的字符串替换为str。
① append(): 用于在字符串末尾添加各种数据,是一个重载方法。
② insert(int offset,int i): 用于在指定位置offset处插入各种数据,是一个重载方法。
③ delete(int start,int end):用于删除从start开始到(end-1)处的字符串。
④ reverse():用于对StringBuffer对象进行颠倒操作。
⑤ replace(int start,int end,String str):将方法的功能是将StringBuffer对象字符串中从start到end-1处的字符串替换为str。
项目实战
每从键盘输入一个新但此后,将其与从现有单词列表中取出的单词逐个比较,在大于该新单词的第1个单词前插入该新单词;
如果新单词比单词列表中所有的单词都打,则直接在单词列表的最后将新单词添加进去。
import java.io.*;
public class StringBufferDemo {
public static void main(String[] args) throws IOException {
StringBuffer words = new StringBuffer(); // 定义一个可变字符串对象words
int wordStart = 0, wordEnd = 0; // 定义与初始化单词开始与结束下标
String tempWord = ""; // 定义每次从缓冲字符串中取出的单词
String newWord = ""; // 存放从键盘输入的单词
System.out.println("每输入一个单词后换行,输入\"end\"结束"); // 提示输入语句
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!(newWord = in.readLine()).equalsIgnoreCase("end")) { // 从键盘输入的单词存放到newWord,输入end时候结束。
wordStart = 0; // 初始化为0,每次都从0开始
while (wordStart < words.length()) { // 该循环将新单词插入字符串中
wordEnd = words.indexOf("", wordStart); // 取下一个单词的结束位置
tempWord = words.substring(wordStart, wordEnd); //取出单词
if (newWord.compareToIgnoreCase(tempWord) > 0) {
wordStart = wordEnd + 1; //若新单词比选出的单词大,定位下一单词
} else {
words.insert(wordStart, newWord + ""); //插入新单词
break; //跳出循环,读取下一个新单词
}
}
if (wordStart >= words.length())
words.append(newWord + ""); //若新单词最大,将其直接添加到最后
}
System.out.println(words); //输出单词序列
}
}