java积累
- java简单实现加减乘除运算
利用Args参数调用,判断输入参数是否合法中用了NumberFormatException这一异常,并且调用了Double.parseDouble()的方法。
public class TestArgs {
public static void main(String[] args) {
if(args.length<3){
System.out.println(
"Usage: java TestArgs \"n1\" \"op\" \"n2\"");
System.exit(-1);
}
try{
double d1 = Double.parseDouble(args[0]);
double d2 = Double.parseDouble(args[2]);
double d = 0;
if(args[1].equals("+")) d = d1+d2;
else if(args[1].equals("-")) d = d1-d2;
else if(args[1].equals("x")) d = d1*d2;
else if(args[1].equals("/")) d = d1/d2;
else{
System.out.println("Error operator!");
System.exit(-1);
}
System.out.println(d);
} catch (NumberFormatException e){
e.printStackTrace();
System.out.println("Error in Numberformat");
}
}
}
2.Bubble Sort(冒泡排序)和Binary Search(二分法查找)
- 注意代码中比较日期的写法,不过不推荐使用该方法
- public static String valueOf(Object obj)
- public String toString()
public class TestDateSort {
public static void main(String[] args) {
Date[] days = new Date[5];
days[0] = new Date(2006, 5, 4);
days[1] = new Date(2006, 7, 4);
days[2] = new Date(2008, 5, 4);
days[3] = new Date(2004, 5, 9);
days[4] = new Date(2004, 5, 4);
Date d = new Date(2006, 7, 4);
//String str = String.valueOf(d);
String str = d.toString();
System.out.println(str);
bubbleSort(days);
for(int i=0; i<days.length; i++) {
System.out.println(days[i]);//直接打印对象相当于调用Object.toString()的方法
}
System.out.println(binarySearch(days, d));
}
public static Date[] bubbleSort(Date[] a){
int len = a.length;
for(int i = len-1;i>=1;i--){
for(int j = 0;j<=i-1;j++){
if(a[j].compare(a[j+1]) > 0){
Date temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
return a;
}
public static int binarySearch(Date[] days, Date d) {
if (days.length==0) return -1;
int startPos = 0;
int endPos = days.length-1;
int m = (startPos + endPos) / 2;
while(startPos <= endPos){
if(d.compare(days[m]) == 0) return m;
if(d.compare(days[m]) > 0) {
startPos = m + 1;
}
if(d.compare(days[m]) < 0) {
endPos = m -1;
}
m = (startPos + endPos) / 2;
}
return -1;
}
}
class Date {
int year, month, day;
Date(int y, int m, int d) {
this.year = y; month = m; day = d;
}
public int compare(Date date) {
return year > date.year ? 1
: year < date.year ? -1
: month > date.month ? 1
: month < date.month ? -1
: day > date.day ? 1
: day < date.day ? -1 : 0;
}
public String toString() {
return "Year:Month:Day -- " + year + "-" + month + "-" + day;
}
}
3.数三退一问题(双向闭环循环)
两种方法,第一种比较好想,第二种是面向对象的思想,需要花点时间理解
- 方法一
public class Count3Quit {
public static void main(String[] args) {
boolean[] arr = new boolean[500];
for(int i=0; i<arr.length; i++) {
arr[i] = true;
}
int leftCount = arr.length;
int countNum = 0;
int index = 0;
while(leftCount > 1) {
if(arr[index] == true) {
countNum ++;
if(countNum == 3) {
countNum = 0;
arr[index] = false;
leftCount --;
}
}
index ++;
if(index == arr.length) {
index = 0;
}
}
for(int i=0; i<arr.length; i++) {
if(arr[i] == true) {
System.out.println(i);
}
}
}
}
- 方法二
public class Count3Quit2 {
public static void main(String[] args) {
KidCircle kc = new KidCircle(500);
int countNum = 0;
Kid k = kc.first;
while(kc.count > 1) {
countNum ++;
if(countNum == 3) {
countNum = 0;
kc.delete(k);
}
k = k.right;
}
System.out.println(kc.first.id);
}
}
class Kid {
int id;
Kid left;
Kid right;
}
class KidCircle {
int count = 0;
Kid first, last;
KidCircle(int n) {
for(int i=0; i<n; i++) {
add();
}
}
//闭环双向循环
void add() {
Kid k = new Kid();
k.id = count;
if(count <= 0) {
first = k;
last = k;
k.left = k;
k.right = k;
} else {
last.right = k;
k.left = last;
k.right = first;
first.left = k;
last = k;
}
count ++;
}
void delete(Kid k) {
if(count <= 0) {
return;
} else if (count == 1) {
first = last = null;
} else {
k.left.right = k.right;
k.right.left = k.left;
if(k == first) {
first = k.right;
} else if( k == last) {
last = k.left;
}
}
count --;
}
}
4.持有对方引用
在稍微复杂的系统中,类与类之间想要相互访问对方的变量,最好的方式是引用对方的对象实例而不是另外储存对方变量的值(面向对象的思想?)。
import java.awt.*;
import java.awt.event.*;
public class TFMath{
public static void main(String[] args){
new TFFrame().launchFrame();
}
}
class TFFrame extends Frame{
TextField num1, num2, num3;
public void launchFrame() {
num1 = new TextField(5);
num2 = new TextField(5);
num3 = new TextField(8);
Label lbPlus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyMonitor(this));
setLayout(new FlowLayout());
add(num1);
add(lbPlus);
add(num2);
add(btnEqual);
add(num3);
pack();
setVisible(true);
}
private class MyMonitor implements ActionListener {
/*
TextField num1, num2, num3;
public MyMonitor(TextField num1, TextField num2, TextField num3){
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
num3.setText(String.valueOf(n1+n2));
}
*/
TFFrame tf = null;
public MyMonitor(TFFrame tf){ //这种 引用方法更高效
this.tf = tf; //this这个关键字其代表的就是对象中的成员变量或者方法。也就是说,
//如果在某个变量前面加上一个this关键字,其指的就是这个对象的成员变量或者方法,
//而不是指成员方法的形式参数或者局部变量。
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(tf.num1.getText());
int n2 = Integer.parseInt(tf.num2.getText());
tf.num3.setText(String.valueOf(n1+n2));
}
}
}
还有一种内部类引用的方法,更为简洁
import java.awt.*;
import java.awt.event.*;
public class TFMath {
public static void main(String[] args) {
new TFFrame().launchFrame();
}
}
class TFFrame extends Frame {
TextField num1, num2, num3;
public void launchFrame() {
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(15);
Label lblPlus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyMonitor());
setLayout(new FlowLayout());
add(num1);
add(lblPlus);
add(num2);
add(btnEqual);
add(num3);
pack();
setVisible(true);
}
private class MyMonitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText()); //内部类可以很方便的访问外部包装类的成员变量和成员方法
int n2 = Integer.parseInt(num2.getText());
num3.setText("" + (n1+n2));
}
}
}
5.代码行数统计
方法一 注意里面的readLines()是读取一行但返回值不包含换行符"\n",可以用endsWith(),但是不能使用startsWith("/*")判断commentLines,因为一行的开头往往包含空格符等符号。(方法一有时并不准确)
package com.company;
import java.io.*;
public class CodeCount {
static long normalLines = 0;
static long commentLines = 0;
static long whiteLines = 0;
public static void main(String[] args) {
File f = new File("D:\\code\\");
File[] codeFiles = f.listFiles();
for (File child : codeFiles){
// System.out.println(child);
if(child.getName().matches(".*\\.java$")) {
System.out.println(child);
parse(child);
}
}
System.out.println("normalLines: "+normalLines);
System.out.println("commentLines: "+commentLines);
System.out.println("whiteLines: "+whiteLines);
}
private static void parse(File f) {
BufferedReader br = null;
boolean comment = false;
try {
br = new BufferedReader(new FileReader(f));
String line = "";
while ((line = br.readLine()) != null) {//readLines() Returns:A String containing the contents of the line,
// not including any line-termination characters,
// or null if the end of the stream has been reached without reading any characters
// System.out.println(line);
if (line.matches("^[\\s&&[^\\n]]*$")) {
whiteLines ++;
} else if (line.contains("/*") && !line.contains("*/")) {
commentLines ++;
comment = true;
} else if (comment) {
commentLines ++;
if (line.endsWith("*/")) {
// System.out.println(line.indexOf("*/"));
comment = false;
}
} else if ((line.contains("/*") && line.contains("*/")) || line.contains("//")) {
commentLines ++;
// if (line.contains("*/")) {
// System.out.println(line.indexOf("/*"));
// }
// if (line.endsWith("*/")) {
// System.out.println(line.indexOf("*/"));
// }
} else {
normalLines ++;
}
}
} /*catch (FileNotFoundException e) {
e.printStackTrace();
}*/ catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try{
br.close();
br = null;
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
方法二 使用String类的trim()方法,之后就可以使用startsWith()方法了。
package com.company;
import java.io.*;
public class CodeCount {
static long normalLines = 0;
static long commentLines = 0;
static long whiteLines = 0;
public static void main(String[] args) {
File f = new File("D:\\code\\");
File[] codeFiles = f.listFiles();
for (File child : codeFiles){
// System.out.println(child);
if(child.getName().matches(".*\\.java$")) {
System.out.println(child);
parse(child);
}
}
System.out.println("normalLines: "+normalLines);
System.out.println("commentLines: "+commentLines);
System.out.println("whiteLines: "+whiteLines);
}
private static void parse(File f) {
BufferedReader br = null;
boolean comment = false;
try {
br = new BufferedReader(new FileReader(f));
String line = "";
while ((line = br.readLine()) != null) {//readLines() Returns:A String containing the contents of the line,
// not including any line-termination characters,
// or null if the end of the stream has been reached without reading any characters
// System.out.println(line);
line = line.trim();
if (line.matches("^[\\s&&[^\\n]]*$")) {
whiteLines ++;
} else if (line.startsWith("/*") && !line.endsWith("*/")) {//else if (line.contains("/*") && !line.contains("*/")) {
commentLines ++;
comment = true;
} else if (comment) {
commentLines ++;
if (line.endsWith("*/")) {
comment = false;
}
} else if ((line.startsWith("/*") && line.endsWith("*/")) || line.startsWith("//")) {
commentLines ++;
} else {
normalLines ++;
}
}
} /*catch (FileNotFoundException e) {
e.printStackTrace();
}*/ catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try{
br.close();
br = null;
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}