A. 用java寫一個程序
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class PrimeNumberFinder {
public static void main(String[] args) {
// 設置范圍
int start = 20000000;
int end = 300000000;
// 用於寫入文件的 BufferedWriter
BufferedWriter writer = null;
try {
// 初始化 BufferedWriter
writer = new BufferedWriter(new FileWriter("primefile.dat"));
// 遍歷范圍內的所有數字
for (int i = start; i <= end; i++) {
// 如果這個數字是素數,寫入文件
if (isPrime(i)) {
writer.write(String.valueOf(i));
writer.newLine();
}
}
} catch (IOException e) {
// 如果出現 IOException,輸出錯誤信息
e.printStackTrace();
} finally {
// 最後關閉 BufferedWriter
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 判斷一個數字是否為素數
public static boolean isPrime(int n) {
// 對於小於 2 的數字,直接返回 false
if (n < 2) {
return false;
}
// 從 2 開始遍歷到 n-1,如果能被 n 整除,則返回 false
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
// 如果執行到這里,說明沒有小於 n 的數字能被 n 整除,返回 true
return true;
}
B. 怎樣用java編寫一個程序
importjava.awt.*;
importjava.awt.event.*;
{
privateLabellName,lPassword;
privateTextFieldtName,tPassword;
privateButtonlogin,rest,exitout;
privateLabellogin_clew;
privateintcount=0;
privateStringmyName="nihao";
privateStringmyPassword="5201314";
publicvoidsetMyNP(Stringn,Stringp){
myName=n;
myPassword=p;
}
publicMyDow(Stringstr){
super(str);
}
publicvoidinit(){
setLayout(null);
setSize(400,300);
setVisible(true);
setResizable(false);
lName=newLabel("姓名");
lName.setBounds(50,70,60,30);add(lName);
lPassword=newLabel("密碼");
lPassword.setBounds(50,120,60,30);add(lPassword);
tName=newTextField("");
tName.setBounds(110,70,200,30);add(tName);
tPassword=newTextField("");
tPassword.setBounds(110,120,200,30);add(tPassword);
login=newButton("登錄");
login.setBounds(90,200,60,30);add(login);
rest=newButton("重輸");
rest.setBounds(170,200,60,30);add(rest);
exitout=newButton("退出");
exitout.setBounds(250,200,60,30);add(exitout);
login_clew=newLabel("");
login.addActionListener(this);
rest.addActionListener(this);
exitout.addActionListener(this);
}
publicvoidactionPerformed(ActionEvente){
if(e.getSource()==login){
if(count<2){
if(tName.getText().equalsIgnoreCase(myName)&&tPassword.getText().equalsIgnoreCase(myPassword)){
removeAll();
add(login_clew);
add(exitout);
exitout.setLabel("確定");
login_clew.setBounds(160,120,200,30);
login_clew.setText("歡迎XX用戶!");
exitout.setBounds(170,220,60,30);
}else{
add(login_clew);
login_clew.setBounds(90,160,200,30);
login_clew.setText("請輸入正確的信息!");
count++;
}
}else{
add(login_clew);
login_clew.setBounds(90,160,200,30);
login_clew.setText("你輸入的次數達到了3次,不能登錄了!");
}
}elseif(e.getSource()==exitout){
System.exit(1);
}else{
lName.setText("");
lPassword.setText("");
}
}
}
publicclassUserLogin{
publicstaticvoidmain(Stringargs[]){
MyDowm=newMyDow("登錄窗口");
m.init();
}
}