「java编程实例」java基础编程实例
本篇文章给大家谈谈java编程实例,以及java基础编程实例对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
- 1、JAVA编程
- 2、JAVA继承实例
- 3、5道简单的JAVA编程题(高分悬赏)
- 4、java编程题目
- 5、java编程
- 6、用java编写一个简单例子,题目如下
JAVA编程
akfucc 很速度啊,不过我也写了,楼主自己比较一下吧。
------------------------- Demo.java ----------------------------
package rectsearch;
import java.text.DecimalFormat;
/**
* @author: shuangwhywhy
* @purpose: 定义一个矩形
* @param: left, bottom, right, top
* @instr: 矩形由四块同样大小的小矩形组成,分别为左下块、右下块、右上块、左上块。
* 所有的矩形都有左、下、右、上四个坐标值表述。
*/
class Rectangle {
public double left, bottom, right, top;
private static DecimalFormat df = new DecimalFormat("0.0000"); //用以格式化输出
public Rectangle (double left, double bottom, double right, double top) {
this.left = left;
this.bottom = bottom;
this.right = right;
this.top = top;
}
/**
* 获得当前矩形的左下块
*/
public Rectangle getLeftBottom () {
return new Rectangle(left, bottom, (left+right)/2, (bottom+top)/2);
}
/**
* 获得当前矩形的右下块
*/
public Rectangle getRightBottom () {
return new Rectangle((left+right)/2, bottom, right, (bottom+top)/2);
}
/**
* 获得当前矩形的右上块
*/
public Rectangle getRightTop () {
return new Rectangle((left+right)/2, (bottom+top)/2, right, top);
}
/**
* 获得当前矩形的左上块
*/
public Rectangle getLeftTop () {
return new Rectangle(left, (bottom+top)/2, (left+right)/2, top);
}
/**
* 判断所给矩形是否被当前矩形完全覆盖
*/
public boolean contains (Rectangle rect) {
if (left rect.left || right rect.right || bottom rect.bottom || top rect.top)
return false;
return true;
}
/**
* 获得当前矩形的字符串表述
* 此处用到了 DecimalFormat 的静态对象以格式化数值
*/
public String toString () {
return ("(" + df.format(left) + ", " + df.format(bottom) + ", " + df.format(right) + ", " + df.format(top) + ")");
}
}
/**
* 此类执行搜索
*/
public class Search {
private Rectangle rectMap, rectTarget;
public Search (Rectangle rectMap, Rectangle rectTarget) {
this.rectMap = rectMap;
this.rectTarget = rectTarget;
validate(); //验证有效性
}
/**
* 验证有效性。输入的矩形须满足以下条件:
* - 不为 null
* - map 完全覆盖 target
* 否则程序报错并退出。
*/
public void validate () {
if (rectMap == null || rectTarget == null) {
System.out.println("Invalid rectangle rectMap = " + rectMap + ", rectTarget = " + rectTarget);
System.exit(0);
} else if (!rectMap.contains(rectTarget)) {
System.out.println("The target rectangle " + rectTarget.toString() + " does not entirely lie inside the map " + rectMap.toString() + ".");
System.exit(0);
}
}
/**
* 公共方法调用私有成员方法 find(Rectangle)
* 外部用此方法是因为这样更符合逻辑
*/
public void find () {
find(rectMap);
}
/**
* 递归缩小搜索区域
* 找到(搜索区域不能完全覆盖目标矩形)时退出程序
* 否则分别对当前 rect 的左下块、右下块、右上块、左上块递归调用此方法。
*/
private void find (Rectangle rect) {
if (!rect.contains(rectTarget)) {
return;
}
System.out.println("---" + rect.toString());
find(rect.getLeftBottom());
find(rect.getRightBottom());
find(rect.getRightTop());
find(rect.getLeftTop());
}
}
-------------------- SearchDemo.java ---------------------------
package rectsearch;
import java.io.*;
import java.util.StringTokenizer;
/**
* 实现类
*/
public class SearchDemo {
public static void main (String args[]) throws IOException, NumberFormatException {
// 获取用户输入 map 的四个坐标:
System.out.print("Enter coordinates of the map (left, bottom, right, top): ");
String input = new BufferedReader(new InputStreamReader(System.in)).readLine();
StringTokenizer strtoken = new StringTokenizer(input, " ");
if (strtoken.countTokens() 4) { //判断输入的是否是 4 个数
System.out.println("Please input 4 double values! Run again!");
System.exit(0);
}
double left = Double.parseDouble(strtoken.nextToken());
double bottom = Double.parseDouble(strtoken.nextToken());
double right = Double.parseDouble(strtoken.nextToken());
double top = Double.parseDouble(strtoken.nextToken());
Rectangle rectMap = new Rectangle(left, bottom, right, top);
// 获取用户输入 target 的四个坐标:
System.out.print("Enter coordinates of the target (left, bottom, right, top): ");
input = new BufferedReader(new InputStreamReader(System.in)).readLine();
strtoken = new StringTokenizer(input, " ");
if (strtoken.countTokens() 4) { //判断输入的是否是 4 个数
System.out.println("Please input 4 double values! Run again!");
System.exit(0);
}
left = Double.parseDouble(strtoken.nextToken());
bottom = Double.parseDouble(strtoken.nextToken());
right = Double.parseDouble(strtoken.nextToken());
top = Double.parseDouble(strtoken.nextToken());
Rectangle rectTarget = new Rectangle(left, bottom, right, top);
System.out.println();
// 实例化搜索类并执行搜索:
Search search = new Search(rectMap, rectTarget);
search.find();
}
}
--------------------------------------------------------------
运行示例:
JAVA继承实例
继承是面向对象编程技术的一块基石,因为它允许创建分等级层次的类。运用继承,你能够创建一个通用类,它定义了一系列相关项目的一般特性。该类可以被更具体的类继承,每个具体的类都增加一些自己特有的东西。在Java 术语学中,被继承的类叫超类(superclass ),继承超类的类叫子类(subclass )。因此,子类是超类的一个专门用途的版本,它继承了超类定义的所有实例变量和方法,并且为它自己增添了独特的元素。
继承一个类,只要用extends 关键字把一个类的定义合并到另一个中就可以了。为了理解怎样继承,让我们从简短的程序开始。下面的例子创建了一个超类A和一个名为B的子类。注意怎样用关键字extends 来创建A的一个子类。
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
该程序的输出如下:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
像你所看到的,子类B包括它的超类A中的所有成员。这是为什么subOb 可以获取i和j 以及调用showij( ) 方法的原因。同样,sum( ) 内部,i和j可以被直接引用,就像它们是B的一部分。
尽管A是B的超类,它也是一个完全独立的类。作为一个子类的超类并不意味着超类不能被自己使用。而且,一个子类可以是另一个类的超类。声明一个继承超类的类的通常形式如下:
class subclass-name extends superclass-name {
// body of class
}
你只能给你所创建的每个子类定义一个超类。Java 不支持多超类的继承(这与C++ 不同,在C++中,你可以继承多个基础类)。你可以按照规定创建一个继承的层次。该层次中,一个子类成为另一个子类的超类。然而,没有类可以成为它自己的超类。
成员的访问和继承
尽管子类包括超类的所有成员,它不能访问超类中被声明成private 的成员。例如,考虑下面简单的类层次结构:
/* In a class hierarchy, private members remain private to their class.
This program contains an error and will not compile.
*/
// Create a superclass.
class A {
int i;
private int j; // private to A
void setij(int x, int y) {
i = x; j = y;
}
}
// A"s j is not accessible here.
class B extends A {
int total; void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
该程序不会编译,因为B中sum( ) 方法内部对j的引用是不合法的。既然j被声明成private,它只能被它自己类中的其他成员访问。子类没权访问它。
注意:一个被定义成private 的类成员为此类私有,它不能被该类外的所有代码访问,包括子类。
更实际的例子
让我们看一个更实际的例子,该例子有助于阐述继承的作用。新的类将包含一个盒子的宽度、高度、深度。
// This program uses inheritance to extend Box.
class Box {
double width; double height; double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume double
volume() {
return width * height * depth;
}
}
BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
该程序的输出显示如下:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
BoxWeight 继承了Box 的所有特征并为自己增添了一个weight 成员。没有必要让BoxWeight 重新创建Box 中的所有特征。为满足需要我们只要扩展Box就可以了。
继承的一个主要优势在于一旦你已经创建了一个超类,而该超类定义了适用于一组对象的属性,它可用来创建任何数量的说明更多细节的子类。每一个子类能够正好制作它自己的分类。例如,下面的类继承了Box并增加了一个颜色属性:
// Here, Box is extended to include color.
class ColorBox extends Box {
int color; // color of box
ColorBox(double w, double h, double d, int c) {
width = w;
height = h;
depth = d;
color = c;
}
}
记住,一旦你已经创建了一个定义了对象一般属性的超类,该超类可以被继承以生成特殊用途的类。每一个子类只增添它自己独特的属性。这是继承的本质。
超类变量可以引用子类对象
超类的一个引用变量可以被任何从该超类派生的子类的引用赋值。你将发现继承的这个方面在很多条件下是很有用的。例如,考虑下面的程序:
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box(); double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
这里,weightbox 是BoxWeight 对象的一个引用,plainbox 是Box对象的一个引用。既然BoxWeight 是Box的一个子类,允许用一个weightbox 对象的引用给plainbox 赋值。
当一个子类对象的引用被赋给一个超类引用变量时,你只能访问超类定义的对象的那一部分。这是为什么plainbox 不能访问weight 的原因,甚至是它引用了一个BoxWeight 对象也不行。仔细想一想,这是有道理的,因为超类不知道子类增加的属性。这就是本程序中的最后一行被注释掉的原因。Box的引用访问weight 域是不可能的,因为它没有定义。
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(i10);
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编程题目
这不都说的很清楚了么。。。。。。。。
自己写吧,也没啥难度。
是完全不知道这个题目再说什么么?
package spring5.source;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class D extends JFrame {
public static void main(String[] args) {
D d = new D();
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.setSize(500, 500);
d.setLayout(new FlowLayout());
TextField t1 = new TextField();
TextField t2 = new TextField();
Button b = new Button("OK");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String v1 = t1.getText();
try {
int n = Integer.parseInt(v1);
Double d = Math.pow(n, 2);
t2.setText(String.valueOf(d.intValue()));
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
t1.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
String v1 = t1.getText();
try {
int n = Integer.parseInt(v1);
Double d = Math.pow(n, 2);
t2.setText(String.valueOf(d.intValue()));
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
});
// KeyListener key_Listener = ;
d.add(t1);
d.add(t2);
d.add(b);
d.setVisible(true);
}
}
少了一个 d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 关闭窗口的
java编程
public class MyArray {
public int[] data;
public MyArray(){
data = new int[10];
}
public MyArray(int n){
data = new int[n];
for(int i=0;in;i++){
data[i] = (int)(Math.random()*1000);
}
}
public MyArray(int[] data){
this.data = data;
}
public void output(){
for(int i=0;idata.length;i++){
System.out.println(data[i]);
}
}
public void sort(){
for(int i=0;idata.length;i++){
for(int j=i+1;jdata.length;j++){
if(data[j]data[i]){
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
}
}
用java编写一个简单例子,题目如下
package test;
public class Student {
private String name;
private String id;
private String clazz;
private int age;
private String address;
/**
* sayHello方法
*/
public void sayHello() {
System.out.println("学号为" + this.id + "的同学的具体信息如下:");
System.out.println("姓名:" + this.name);
System.out.println("班级:" + this.clazz);
System.out.println("年龄:" + this.age);
System.out.println("家庭住址:" + this.address);
}
/**
* 测试方法
*
* @param args
*/
public static void main(String[] args) {
// 第一问
Student student = new Student();
student.setAddress("百度知道");
student.setAge(1);
student.setClazz("一班");
student.setId("071251000");
student.setName("lsy605604013");
student.sayHello();
// 第二问
Student studentNew = new Student();
studentNew.setAddress("搜搜知道");
studentNew.setAge(2);
studentNew.setClazz("二班");
studentNew.setId("071251001");
studentNew.setName("lady");
if (student.getAge() studentNew.getAge())
studentNew.sayHello();
else if (student.getAge() studentNew.getAge())
student.sayHello();
else
System.out.println("两人一样大");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
关于java编程实例和java基础编程实例的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。