這個題考察的是面向對象三大特性之一的繼承。
子類繼承父類。
項目結構如何所示:
我是馮修遠,如果我的答案對您有幫助的話,請採納以幫助更多的人,如果還有其它的問題,也請關注我,私信我,謝謝!
Ⅱ 5道簡單的JAVA編程題(高分懸賞)
很詳細的幫你寫下,呵呵,所以要給分哦!
1、
(1)源程序如下:
public class One {
public static void main(String[] args) {
String name = "張三";
int age = 23;
char sex = '男';
String myclass = "某某專業2班";
System.out.println("姓名:" + name);
System.out.println("姓名:" + age);
System.out.println("姓名:" + sex);
System.out.println("姓名:" + myclass);
}
}
(2)
編寫完程序的後綴名是.java,如本題,文件名就是One.java。
開始\運行\cmd,進入「命令提示符窗口」,然後用javac編譯器編譯.java文件,語句:javac One.java。
(3)
編譯成功後,生成的文件名後綴是.class,叫做位元組碼文件。再用java解釋器來運行改程序,語句:java One
2、編寫程序,輸出1到100間的所有偶數
(1)for語句
public class Two1 {
public static void main(String[] args) {
for(int i=2;i<=100;i+=2)
System.out.println(i);
}
}
(2)while語句
public class Two2 {
public static void main(String[] args) {
int i = 2;
while (i <= 100) {
System.out.println(i);
i += 2;
}
}
}
(3)do…while語句
public class Two3 {
public static void main(String[] args) {
int i = 2;
do {
System.out.println(i);
i += 2;
}while(i<=100);
}
}
3、編寫程序,從10個數當中找出最大值。
(1)for循環
import java.util.*;
public class Three1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int max = 0;
for (int i = 0; i < 10; i++) {
System.out.print("輸入第" + (i + 1) + "個數:");
number = input.nextInt();
if (max < number)
max = number;
}
System.out.println("最大值:" + max);
}
}
(2)while語句
import java.util.*;
public class Three2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int i = 0;
while (i < 10) {
System.out.print("輸入第" + (i + 1) + "個數:");
number = input.nextInt();
if (max < number)
max = number;
i++;
}
System.out.println("最大值:" + max);
}
}
(3)do…while語句
import java.util.*;
public class Three3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int i = 0;
do {
System.out.print("輸入第" + (i + 1) + "個數:");
number = input.nextInt();
if (max < number)
max = number;
i++;
}while(i<10);
System.out.println("最大值:" + max);
}
}
4、編寫程序,計算從1到100之間的奇數之和。
(1)for循環
public class Four1 {
public static void main(String[] args) {
int sum=0;
for(int i = 1;i<=100;i+=2){
sum+=i;
}
System.out.println("1~100間奇數和:" + sum);
}
}
(2)while語句
public class Four2 {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i += 2;
}
System.out.println("1~100間奇數和:" + sum);
}
}
(3)do…while語句
public class Four3 {
public static void main(String[] args) {
int sum = 0;
int i = 1;
do {
sum += i;
i += 2;
} while (i <= 100);
System.out.println("1~100間奇數和:" + sum);
}
}
5、
(1)什麼是類的繼承?什麼是父類?什麼是子類?舉例說明。
繼承:是面向對象軟體技術當中的一個概念。如果一個類A繼承自另一個類B,就把這個A稱為"B的子類",而把B稱為"A的父類"。繼承可以使得子類具有父類的各種屬性和方法,而不需要再次編寫相同的代碼。在令子類繼承父類的同時,可以重新定義某些屬性,並重寫某些方法,即覆蓋父類的原有屬性和方法,使其獲得與父類不同的功能。另外,為子類追加新的屬性和方法也是常見的做法。繼承需要關鍵字extends。舉例:
class A{}
class B extends A{}
//成員我就不寫了,本例中,A是父類,B是子類。
(2)編寫一個繼承的程序。
class Person {
public String name;
public int age;
public char sex;
public Person(String n, int a, char s) {
name = n;
age = a;
sex = s;
}
public void output1() {
System.out.println("姓名:" + name + "\n年齡:" + age + "\n性別:" + sex);
}
}
class StudentPerson extends Person {
String school, department, subject, myclass;
public StudentPerson(String sc, String d, String su, String m, String n,
int a, char s) {
super(n, a, s);
school = sc;
department = d;
subject = su;
myclass = m;
}
public void output2() {
super.output1();
System.out.println("學校:" + school + "\n系別:" + department + "\n專業:"
+ subject + "\n班級:" + myclass);
}
}
public class Five2 {
public static void main(String[] args) {
StudentPerson StudentPersonDemo = new StudentPerson("某某大學", "某某系別",
" 某專業", "某某班級", " 張三", 23, '男');
StudentPersonDemo.output2();
}
}
Ⅲ Java編程題,求解
// 上源碼
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
/**
* 數字鍵 0-9鍵 *鍵 #鍵
*/
private static String[][] digits = new String[][]{
// 0
{},
// 1
{},
// 2
{"A", "B", "C"},
// 3
{"D", "E", "F"},
// 4
{"G", "H", "I"},
// 5
{"J", "K", "L"},
// 6
{"M", "N", "O"},
// 7
{"P", "Q", "R", "S"},
// 8
{"T", "U", "V"},
// 9
{"W", "X", "Y", "Z"},
// *
{},
// #
{},
};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String inputs;
String[] arr;
System.out.print("請輸入按鍵數字(多個數字空格隔開):");
while (null != (inputs = scanner.nextLine())) {
if ("exit".equalsIgnoreCase(inputs) || "quit".equalsIgnoreCase(inputs)) {
System.out.println("退出程序");
System.exit(1);
}
// 檢查args輸入參數是否合法
if (checkInput(inputs.split(" "))) {
arr = inputs.trim().split(" ");
// 查找輸入鍵的所有字母組合
List<String[]> inputCharList = new ArrayList<>();
for (String digit : arr) {
// *#01沒有字母
if ("*#01".indexOf(digit) >= 0) {
continue;
}
inputCharList.add(digits[Integer.parseInt(digit)]);
}
if (!inputCharList.isEmpty()) {
combineChars("", inputCharList);
System.out.println();
} else {
System.out.println("輸入的數字沒有字母組合。");
}
} else {
System.out.println("按鍵輸入不正確,請輸入0-9 * #鍵。");
}
System.out.print("請輸入按鍵數字(多個數字空格隔開):");
}
}
/**
* 遞歸查找所有字母組合
* @param headerChar
* @param inputCharList
*/
private static void combineChars(String headerChar, List<String[]> inputCharList) {
if (inputCharList.size() == 1) {
for (String ch : inputCharList.get(0)) {
System.out.print(headerChar + ch + " ");
}
} else {
for (String ch : inputCharList.get(0)) {
combineChars(headerChar + ch, inputCharList.subList(1, inputCharList.size()));
}
}
}
/**
* 校驗輸入是否合法
*
* @param args
* @return
*/
static boolean checkInput(String[] args) {
String validInputs = "0123456789*#";
boolean isValid = true;
for (String arg : args) {
if (arg.length() != 1 || validInputs.indexOf(arg) < 0) {
isValid = false;
break;
}
}
return isValid;
}
}
運行效果
題目里只說了輸入兩個數字的情況,輸入* # 1 0這里我直接視為無效輸入了(忽略掉了),對於輸入超過兩個數字以上的情況也能按要求輸出。(考慮到輸入的數字個數不確定因素,這里用到了遞歸,如果確定只有1或2個數字輸入,代碼會簡介很多,也不需要遞歸)
Ⅳ java編程題 本人新手,求詳解。
先看下最終的結果吧,是不是你想要的?
其中,Student是父類,PostGraate是子類,繼承自父類Student,Main是主類,用於創建對象以及把這些對象的功能調用起來。
---------------------------Student代碼如下:------------------------------
/**
* 學生類
* @author 逍遙
*
*/
public class Student {
//學號
private int sId;
//姓名
private String sName;
//數學成績
private double mathScore;
//計算機成績
private double computerScore;
/**
* 獲取學號
* @return
*/
public int getsId() {
return sId;
}
/**
* 設置學號
* @param sId
*/
public void setsId(int sId) {
this.sId = sId;
}
/**
* 獲取姓名
* @return
*/
public String getsName() {
return sName;
}
/**
* 設置姓名
* @param sName
*/
public void setsName(String sName) {
this.sName = sName;
}
/**
* 獲取數學成績
* @return
*/
public double getMathScore() {
return mathScore;
}
/**
* 設置數學成績
* @param mathScore
*/
public void setMathScore(double mathScore) {
this.mathScore = mathScore;
}
/**
* 獲取計算機成績
* @return
*/
public double getComputerScore() {
return computerScore;
}
/**
* 設置計算機成績
* @param computerScore
*/
public void setComputerScore(double computerScore) {
this.computerScore = computerScore;
}
/**
* 輸出成員變數(4個成員變數)的信息。
*/
public void print(){
System.out.println("學號:"+sId);
System.out.println("姓名:"+sName);
System.out.println("計算機成績:"+mathScore);
System.out.println("數學成績:"+computerScore);
}
}
---------------------------Student代碼結束------------------------------
---------------------------PostGraate代碼如下:------------------------------
/**
* 研究生類
* @author 逍遙
*
*/
public class PostGraate extends Student{
//導師姓名
private String tName;
//研究方向
private String ResearchDirection;
/**
* 獲取導師姓名
* @return
*/
public String gettName() {
return tName;
}
/**
* 設置導師姓名
* @param tName
*/
public void settName(String tName) {
this.tName = tName;
}
/**
* 獲取研究方向
* @return
*/
public String getResearchDirection() {
return ResearchDirection;
}
/**
* 設置研究方向
* @param researchDirection
*/
public void setResearchDirection(String researchDirection) {
ResearchDirection = researchDirection;
}
/**
* 研究生類重寫父類的void print()方法,功能是輸出成員變數(6個成員變數)的信息
*/
@Override
public void print() {
// TODO Auto-generated method stub
super.print();
System.out.println("導師姓名:"+tName);
System.out.println("研究方向:"+ResearchDirection);
}
}
---------------------------PostGraate代碼結束------------------------------
---------------------------Main代碼如下:------------------------------
import java.util.Scanner;
/**
* 主類
* @author 逍遙
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//用於獲取從鍵盤上輸入的信息
Scanner input=new Scanner(System.in);
//創建一個Student類的對象
Student student=new Student();
//從鍵盤上輸入其屬性信息
System.out.print("請輸入學生的學號:");
student.setsId(input.nextInt());
System.out.print("請輸入學生的姓名:");
student.setsName(input.next());
System.out.print("請輸入學生的數學成績:");
student.setMathScore(input.nextDouble());
System.out.print("請輸入學生的計算機成績:");
student.setComputerScore(input.nextDouble());
//並且通過其print方法輸出這些信息;
student.print();
//創建一個PostGraate類的對象
PostGraate postGraate=new PostGraate();
//從鍵盤上輸入其屬性信息
System.out.print("請輸入研究生的學號:");
postGraate.setsId(input.nextInt());
System.out.print("請輸入研究生的姓名:");
postGraate.setsName(input.next());
System.out.print("請輸入研究生的數學成績:");
postGraate.setMathScore(input.nextDouble());
System.out.print("請輸入研究生的計算機成績:");
postGraate.setComputerScore(input.nextDouble());
System.out.print("請輸入研究生的導師姓名:");
postGraate.settName(input.next());
System.out.print("請輸入研究生的研究方向:");
postGraate.setResearchDirection(input.next());
//並且通過其print方法輸出這些信息。
postGraate.print();
}
}
---------------------------Main代碼結束------------------------------
=================知識點的簡單總結=================
本題考察的知識點是面向對象的三大特性之一:繼承。
Student為父類,包含了學號、姓名、數學成績和計算機成績4個屬性,以及一個print()方法。
PostGraate 繼承父類的時候,繼承了父類中的所有方法,因為方法我都是用的public,而屬性繼承不了,因為我在父類中用了封裝,所有屬性都用private修飾了,想訪問屬性的話,必須通過get、set方法,這里,我重寫了父類中的print方法,通過super.print();調用了父類中的print()方法。
最後就是Main類,提供了main方法作為入口函數,用於按要求聲明這些對象以及去調用對象中的方法。
Ⅳ java編程題
1.package test;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
String str = "afdjasdg&&&&&$$jfsjdfjdjjdjdjdjdjdj";
int max=0;
Object chars=null;
Map tree = new TreeMap();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if ((ch >= 1 && ch <= 255) ) {
if (!tree.containsKey(ch)) {
tree.put(ch, new Integer(1));
} else {
Integer in = (Integer) tree.get(ch) + 1;
tree.put(ch, in);
}
}
}
Iterator tit = tree.keySet().iterator();
while (tit.hasNext()) {
Object temp = tit.next();
if(max<=Integer.parseInt(tree.get(temp)+""))
{
max=Integer.parseInt(tree.get(temp)+"");
chars=temp;
}
}
System.out.print(chars.toString() + "出現" + max + "次");
}
}
只要用assic碼做范圍就可以了.任何字元都可以過濾.
2.方法很多,hashmap或是arraylist,數組都可以的.就是對應關系而已.
package test;
public class ListTest {
static String[] to_19 = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen" };
static String[] tens = { "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety" };
static String[] denom = { "", "thousand ", "million", "billion",
"trillion", "quadrillion", "quintillion", "sextillion",
"septillion", "octillion", "nonillion", "decillion", "undecillion",
"odecillion", "tredecillion", "quattuordecillion",
"sexdecillion", "septendecillion", "octodecillion",
"novemdecillion", "vigintillion" };
public static void main(String[] argv) throws Exception {
long tstValue = 12345;
ListTest itoe = new ListTest();
System.out.println(itoe.english_number(tstValue));
}
private String convert_nn(int val) {
if (val < 20) return to_19[val];
int flag = val / 10 - 2; if (val % 10 != 0)
return tens[flag] + "-" + to_19[val % 10];
else return tens[flag];
}
private String convert_nnn(int val) {
String word = "";
int rem = val / 100;
int mod = val % 100;
if (rem > 0) {word = to_19[rem] + " hundred ";}
if (mod > 0) {word = word + convert_nn(mod);}
return word;
}
public String english_number(long val) {
if (val < 100) {System.out.println((int) val);return convert_nn((int) val);}
if (val < 1000) {return convert_nnn((int) val); }
for (int v = 0; v < denom.length; v++) {
int didx = v - 1;
long dval = new Double(Math.pow(1000, v)).longValue();
if (dval > val) {
long mod = new Double(Math.pow(1000, didx)).longValue();
int l = (int) (val / mod);
long r = (long) (val - (l * mod));
String ret = convert_nnn(l) + " " + denom[didx];
if (r > 0) {ret = ret + ", " + english_number(r);}
return ret;
}
}
return null;
}
}
Ⅵ Java的編程題目,在線等,急急急
先做兩個比較簡單的先用:
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Function {
/**
* 設計一個方法,完成字元串的解析。方法定義為:public void myParseString(String inputStr);
* 對於給定的字元串,取得字元串內的各個整數(不考慮小數,),然後將取得的數排序,按從小到大依次列印出來。
* @param args
*/
public static void main(String[] args) {
String s = "aa789bB22cc345dd;5.a";
new Function().myParseString(s);
}
public void myParseString(String inputStr){
String mathregix="\\d+";//數字
Vector vector=new Vector();
Pattern fun=Pattern.compile(mathregix);
Matcher match = fun.matcher(inputStr);
while (match.find()) {
vector.add(match.group(0));
}
Object[] obj=vector.toArray();
int[] result=new int[obj.length];
for (int i = 0; i < obj.length; i++) {
result[i]=Integer.parseInt((String) obj[i]);
}
Arrays.sort(result);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
}
import java.util.Date;
/**
* 有一個學生類(Student),其有四個私有屬性,分別為:
* 學號no,字元串型;
* 姓名name,字元串型;
* 年齡age,整型;
* 生日birthday,日期型;
* 請:
* 1) 按上面描述設計類;
* 2) 定義對每個屬性進行取值,賦值的方法;
* 3) 要求學號不能為空,則學號的長度不能少於5位字元,否則拋異常;
* 4) 年齡范圍必須在[1,500]之間,否則拋出異常;
*/
public class Student {
private String no;
private String name;
private int age;
private Date birthday;
public int getAge() {
return age;
}
public void setAge(int age) throws Exception {
if(age<1||age<500)throw new Exception("年齡不合法。");
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) throws Exception {
if(no==null)throw new Exception("學號不能為空!");
if(no.length()<5)throw new Exception("學號不能少於五位!");
this.no = no;
}
}
二、三題
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
/**
* 2. 設計一個GUI界面,要求打界面如下:
*點擊文件->打開,打開文件選擇器,選擇打開給定的java.txt文件,將文件內所有a-z,A-Z之間的字元顯示在界面的文本區域內。
* 3. 設置一個GUI界面,界面如下:
* 點擊文件->保存,打開文件選擇窗體,選擇一個保存路徑,將本界面文本區域內輸入的內容進行過濾,將所有非a-z,A-Z之間的字元保存到C盤下的java.txt文件內。
* Java.txt文件內容如下:
* 我們在2009年第2學期學習Java Programming Design,於2009-6-16考試。
*
*
*
*/
public class FileEditer extends javax.swing.JFrame implements ActionListener {
private JMenuBar menubar;
private JMenu file;
private JMenuItem open;
private JTextArea area;
private JMenuItem save;
private JFileChooser jfc;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
FileEditer inst = new FileEditer();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public FileEditer() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
area = new JTextArea();
getContentPane().add(area, BorderLayout.CENTER);
area.setText("文本區");
}
{
menubar = new JMenuBar();
setJMenuBar(menubar);
{
file = new JMenu();
menubar.add(file);
file.setText("文件");
file.setPreferredSize(new java.awt.Dimension(66, 21));
{
open = new JMenuItem();
file.add(open);
open.setText("打開");
open.setBorderPainted(false);
open.setActionCommand("open");
open.addActionListener(this);
}
{
save = new JMenuItem();
file.add(save);
save.setActionCommand("save");
save.setText("保存");
save.addActionListener(this);
}
}
}
{
jfc=new JFileChooser();
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
if("open".equals(e.getActionCommand())){
int result=jfc.showOpenDialog(this);
if(result==jfc.APPROVE_OPTION){
File file=jfc.getSelectedFile();
try {
byte[] b=new byte[1024];
FileInputStream fis=new FileInputStream(file);
fis.read(b);
fis.close();
String string=new String(b,"GBK");
string=string.replaceAll("[^a-zA-Z]*", "");
area.setText(string.trim());
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException es) {
// TODO Auto-generated catch block
es.printStackTrace();
}
}
}else if("save".equals(e.getActionCommand())){
int result=jfc.showSaveDialog(this);
if(result!=jfc.APPROVE_OPTION)return;
File file=jfc.getSelectedFile();
try {
if(!file.exists()){
file.createNewFile();
}
String string = area.getText();
string=string.replaceAll("[a-zA-Z]*", "");
byte[] b=string.getBytes();
FileOutputStream fis=new FileOutputStream(file);
fis.write(b);
fis.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException es) {
// TODO Auto-generated catch block
es.printStackTrace();
}
}
}
}
Ⅶ 求一個java編程題的答案
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Student {
private String id;
private String name;
private boolean isMale;
private Date birth;
public Student() {
super();
}
public Student(String id, String name, boolean isMale, Date birth) {
super();
this.id = id;
this.name = name;
this.isMale = isMale;
this.birth = birth;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isMale() {
return isMale;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", isMale=" + isMale + ", birth=" + birth + "]";
}
}
public class StudentTest {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Student stu = new Student("00001", "Tom", true, dateFormat.parse("2000-01-01"));
System.out.println(stu);
}
}
Ⅷ java簡單編程題,有追加分
第一題,x和n從命令行作為參數輸入:
public class Test1{
public static void main(String[] args){
int argLen = args.length;
//判斷是否至少傳入了兩個參數
if (argLen < 2){
System.out.println("請輸入兩個整型參數");
return;
}
int x = 0;
int n = 0;
//轉換傳遞進來的參數,如果輸入的參數不合法,不能轉換為int型,則Integer.parseInt方法會拋出NumberFormatException異常
try{
x = Integer.parseInt(args[0]);
n = Integer.parseInt(args[1]);
}
catch(NumberFormatException e)
{
System.out.println("輸入的參數不是整數");
System.exit(1);
}
//判斷x和n的值是否是正數
if (x<=0 || n<=0)
{
System.out.println("不能輸入負值或0,請輸入兩個正整數");
System.exit(1);
}
//列印轉換後的x和n
System.out.println("你輸入的x和n分別為: " + x + ", " + n);
/*
y=1+x/1+x*x*x/3+......+x^n/n
根據公式計算結果。由於公式中y增長的很快,所以我們定義一個double型的變數存儲結果的值。但仍然很有可能溢出。必要的話可以使用math包中的類來進行任意長度和精度的處理,但這里就不麻煩了。
*/
double y = 1.0;
for (int i=1; i<=n; i+=2)
{
y += Math.pow(x, i)/(double)i;
}
//列印結果
System.out.println("根據公式y=1+x/1+x*x*x/3+......+x^n/n所計算出的結果為: " + y);
} // main()
} /* Test1 */
第二題,需要的test11.html文件內容如下:
<html>
<head>
<title>Test11 demo</title>
</head>
<body>
<applet width="300" height="400" code="Test11.class"></applet>
</body>
</html>
然後使用appletviewer test11.html瀏覽小應用程序(在瀏覽器中可能不能正常運行)。
java代碼如下:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Label;
public class Test11 extends Applet{
//定義文字所在位置與頂部的距離
private int posY = 200;
private Label textsLabel = new Label("我猜你將看到這句話一直在滾動");
public void init()
{
textsLabel.setBounds(50, 200, 200, 30);
this.add(textsLabel);
//啟動新線程
SecThread st = new SecThread();
st.start();
} // init()
public void paint(Graphics g){
super.paint(g);
} //paint()
//定義一個內部類,以啟動一個新的線程
private class SecThread extends Thread{
public void run()
{
while(true){
//讓當前線程休眠50毫秒,注意sleep方法會拋出InterruptedException異常
try{
Thread.sleep(50);
}
catch(InterruptedException e){
System.out.println("執行過程中出錯");
System.exit(1);
}
//設置文字的新位置
posY -= 5;
//判斷是否小於0(即已經到達頂部),如果小於0則重置為400
posY = (posY<=0?400:posY);
textsLabel.setBounds(50, posY, 200, 30);
Test11.this.repaint();
}
}
}
} /* Test2 */
3, 4兩題實在很簡單,略過了。
找到你的帖子了!
將3,和4也寫一下:
3.運行方法看2:
import java.applet.Applet;
import java.awt.Graphics;
public class Test111 extends Applet
{
public void paint(Graphics g)
{
for (int i=1; i<=10; i++) //畫橫線
{
g.drawLine(20, i*20, 200, i*20);
}
for (int j=1; j<=10; j++) //畫豎線
{
g.drawLine(j*20, 20, j*20, 200);
}
}
}
4. 代碼如下:(你說已經寫好的程序怎麼改成applet。記住一點,applet在運行時自動調用init、start和paint方法,而通常的應用程序調用main方法。只要將main方法中的內容妥善地移到這三個方法中就可以了。但修改的時候要注意,不要引入錯誤。)
//任意輸入三個數,可以有小數,然後比較它們的大小
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Button;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
public class Test1111 extends Applet
{
public void paint(Graphics g)
{
this.setLayout(null);
Button btn = new Button("開始輸入");
btn.setBounds(100, 130, 100, 30);
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sort();
}
});
this.add(btn);
}
private void sort()
{
//3個元素的字元串數組,存放輸入的數
String[] numberStrs = new String[3];
for (int i=0; i<numberStrs.length; i++)
{
//如果輸入時按了取消按鈕,則繼續提示輸入
while(numberStrs[i] == null)
{
numberStrs[i] = JOptionPane.showInputDialog("請輸入第 " + (i+1) + " 個數");
}
}
//定義3個元素的double型數組,存放轉換後的值
double[] numbers = new double[3];
try
{
for (int j=0; j<numbers.length; j++)
{
numbers[j] = Double.parseDouble(numberStrs[j]);
}
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "輸入的不是數字!"
, "ERROR", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
String result = "";
result += "你輸入的數字為: ";
for (int k=0; k<numbers.length-1; k++)
{
result += numbers[k] + ", ";
}
result += numbers[numbers.length-1] + "\n";
//簡單點,使用冒泡排序
for (int i=1; i<numbers.length; i++)
{
for (int j=0; j<numbers.length-1; j++)
{
if (numbers[j] > numbers[j+1])
{
double temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
}
}
}
result += "排序後的數字為: ";
for (int k=0; k<numbers.length-1; k++)
{
result += numbers[k] + ", ";
}
result += numbers[numbers.length-1];
//輸出結果
JOptionPane.showMessageDialog(null, result, "Result", JOptionPane.PLAIN_MESSAGE);
}
}
Ⅸ java考試,求編程題步驟!!!
題目一:
參考代碼
importjava.util.Scanner;
publicclassJiaFaDemo{
publicstaticvoidmain(String[]args){
intx=(int)(Math.random()*100);
inty=(int)(Math.random()*100);
System.out.println(x+"+"+y+"="+(x+y));//自動答題58+4=62
//System.out.print(x+"+"+y+"=");//人工輸入答題需要導入包importjava.util.Scanner;
//Scannerinput=newScanner(System.in);
//intz=input.nextInt();
//if(z==(x+y)){
//System.out.println("回答正確");
//}else{
//System.out.println("回答錯誤");
//}
}
}
輸出
58+4=62
題目二
publicclassJiShuDemo{
publicstaticvoidmain(String[]args){
intsum=0;
for(inti=1;i<=50;i++){
if(i%2!=0){//不能被2整除的數是奇數
sum+=i;
}
}
System.out.println("1~50間奇數和="+sum);
}
}
輸出
1~50間奇數和=625