http://huipochu87.googlepages.com/prime.html
花了一晚,終於完成了到出 1至 1000之間的質數這一份java功課。
單看功課的核心,其實不難,用 for loop 檢查餘數就可以了。
String print ="";
int counter_1;
int counter_2;
int TestNo;
int remainder;
int test;
int pr_check = 0;
//Check the number from 2 to 1000, if it is prime.
for (counter_1 = 2; counter_1 <= 1000; counter_1++ ){
TestNo = counter_1;
test = 0;
//Check the remainders of each number dividing from 1 to itself.
for (counter_2 = 1; counter_2 <= TestNo; counter_2++ ){
remainder = TestNo % counter_2;
if (remainder == 0)
++test; //count the number of remainders
else;
}
//if only 2 remainders, it is prime.
if (test == 2){
++pr_check;
if (pr_check % 5 != 0) { //check for line break, 5 num in one line.
print += "\t" + TestNo ;
} else
print += "\t" + TestNo + "\n";
}
}
在這一段裡面,除了 print out 的指令之外,java 的寫法基本與 c 相同。這部分很容易。
可是,功課要求是要寫帶捲軸的 JApplet ... 這難倒我了 =.=
老師好像沒有教過吧,筆記的例子亦是 java,而不是 JApplet。
網上找了很久,終於在
java.poac.ac.cn 找到可參考的例子。
並意外地找到使 JApplet 可以直接運行的方法。
//JFrame for running JApplet without the html file.
public static void main(String[] args) {
run(new prime(), 600, 500);
}
public static void run(JApplet applet, int width, int height) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
至於帶捲軸的 JApplet,主要是要建立一個 JTextArea,再建立一個 JScrollPane,最後是一個 Container。
之後,JTextArea 承載內容,JScrollPane 承載 JTextArea,Container 承載 JScrollPane。
唉,真麻煩。希望我會記得啦。
http://huipochu87.googlepages.com/prime.java
|