(Compulsory !!!!!!!!) JAVA most most most most most most most most most most basic questions

1. Press the following requirements programming.

(1) define a Student class, which contains student number (stuNo), name (stuName), performance (stuMark) three member variables.

(2) adding a constructor for the class Student, initialize all member variables.

(3) to add four members of the Student class methods were used to obtain student number (getStuNo), to a name (getStuName), to obtain the results (getStuMark), modify the results (modiStuMark).

(4) Based on the above program is to create an object of the class Student st1, and write a complete program for each class using Student method. (Or to create separate execution class Executive class class as Student)

//定义Student类,此时文件名为“Student.java”
public class Student {
	public int stuNo;
	public String stuName;
	public int stuMark;
//含有学号(stuNo)、姓名(stuName)、成绩(stuMark)三个成员变量
	public Student(int stuNo,String stuName,int stuMark){
		this.stuNo=stuNo;
		this.stuName=new String(stuName);//string字符串初始化
		this.stuMark=stuMark;
	}//添加一个构造函数(函数名与类名相同),初始化所有的成员变量
	int getStuNo(){
		return stuNo;
	}
	String getStuName(){
		return stuName;
	}
	int getStuMark(){
		return stuMark;
	}//以上三个均是无参返回
	int modiStuMark(int stuMark){
		return this.stuMark=stuMark;//含参返回
	}//添加四个成员方法,
//分别用于获得学号(getStuNo)获得姓名(getStuName)获得成绩(getStuMark)修改成绩(modiStuMark)
	public static void main(String[] args) {
		Student stl=new Student(5132,"lmw",99);
		stl.getStuMark();
		stl.getStuName();
		stl.getStuMark();//调用三个方法
		System.out.println(stl.stuName+" "+stl.stuNo+" "+stl.stuMark);
		stl.modiStuMark(100);
		System.out.println(stl.stuName+" "+stl.stuNo+" "+stl.stuMark);
        //Student作为执行类
	}
}

2. Write a program according to the following requirements.

(1) the design of a product data type PClass, wherein the member comprises two variables: Product Number (int pNumber), Price (double pPrice); two members method comprising: displaying number showNumber () and a display monovalent showPrice (); and two pClass constructor () and pClass (int number, double price).

(2) design a complete Java program uses the class PClass on the question of establishing a Pclass p class objects, namely PClass p = new PClass (1,1000.0). Then use showNumber () method of the product number is displayed using showPrice () method monovalent displayed. (Or to create separate execution class Executive class as class PClass)

//定义商品数据类PClass,此时文件名为“PClass.java”
public class PClass {
	int pNumber;
	double pPrice;
//两个成员变量:商品编号(int pNumber)单价(double pPrice)
	void showNumber(){
		System.out.println("商品的编号是:"+pNumber);
	}
	void showPrice(){
		System.out.println("商品的单价是:"+pPrice);
	}
//两个成员方法:显示编号showNumber()和显示单价showPrice()
	PClass(){}//空的构造函数
	PClass(int number,double price){
		pNumber=number;
		pPrice=price;
	}//初始化赋值
	public static void main(String[] args) {
		PClass p=new PClass(1,1000.0);//对象必须被用,否则会报错
		p.showNumber();
		p.showPrice();
	}//把PClass类作为执行类
}

3. Create a class, a method in which the definition of print (int a) printing a given integer, and reload the print method, in order to complete the following requirements, and then write a complete program.

(1) printing a given number of type double.

(2) Print two given integer.

(3) printing a string.

Design a complete Java program using the above method. (Or to create separate execution class Executive class of this class as)

//定义类print,此时文件名为“print.java”
public class print {
	void print(int a){
		System.out.println("a="+a);
	}
	void print(double b){
		System.out.println("double b="+b);
	}
	void print(int c,int d){
		System.out.println("int c="+c);
		System.out.println("int d="+d);
	}
	void print(String e){
		System.out.println("String e="+e);
	}
	//重载print方法
	public static void main(String[] args) {
		print printf=new print();
		printf.print(1);
		printf.print(2.0);
		printf.print(3,4);
		printf.print("lmw");
    }//把本类作为执行类
}

4. Write program segment following claims.

(1) Design a product class inherits WClass PClass data classes in question 2, wherein the increase in the member variable commercial grade (int pStage) members and methods showStage (), two constructors WClass () and WClass (int number, double price, int stage).

(2) design a complete program using Java classes WClass, establishing a class object WClass w, i.e. WClass w = new WClass (1,1000.0,2). And then were used showNumber (), showPrice (), showStage () method of the product number, unit price and rank is displayed. (Or to create separate execution class Executive class of this class as)

//定义商品数据类PClass,此时文件名为“lmw.java”
class PClass {
	int pNumber;
	double pPrice;

	// 两个成员变量:商品编号(int pNumber)单价(double pPrice)
	void showNumber() {
		System.out.println("商品的编号是:" + pNumber);
	}

	void showPrice() {
		System.out.println("商品的单价是:" + pPrice);
	}
	// 两个成员方法:显示编号showNumber()和显示单价showPrice()
	PClass(){
	}// 空的构造函数

	PClass(int number, double price) {
		pNumber = number;
		pPrice = price;
	}// 初始化赋值
}
class WClass extends PClass {//定义一个类WClass继承商品数据类PClass
	int pStage;//增加成员变量商品等级(int pStage)
	void showStage(){//增加成员方法showStage()
		System.out.println("商品等级是:"+pStage);
	}
//两个构造函数WClass()和WClass(int number,double price,int stage)
		WClass() {}
		WClass(int number,double price,int stage){
			pNumber=number;
			pPrice=price;
			pStage=stage;
		}
}
public class lmw{
	public static void main(String[] args){
		WClass w=new WClass(1,1000.0,2);//对象必须被用,否则会报错
		w.showNumber();
		w.showPrice();
		w.showStage();
	}
}

5. Press the following requirements to prepare block, then write complete Java program implementation.

(1) Design a bank account class BankAccount, which contains a member variable of type double mRate, represents the bank deposit interest rates, and define setRate (double rate) method to set interest rates on deposits and prints.

Subclass (2) create a class BankAccount representation of LoanAccount loan account, hidden in a subclass member variables in the parent class mRate, and cover member method setRate (double rate) in the parent class to set lending rates and print.

(3) defined message () method in the subclass LoanAccount, setRate method call parent class and subclasses, respectively.

Create separate execution class or classes present as the execution class.

//文件名为“lmw.java”
class BankAccount{
	double mRate;
	void setRate(double rate){
		mRate=rate;
		System.out.println("父类利润:"+mRate);
	}
}
class LoanAccount extends BankAccount{
	double mRate;//只要子类中声明的变量和父类同名,子类就隐藏了父类的成员变量
	void setRate(double rate){
		mRate=rate;
		System.out.println("子类利润:"+mRate);
	}//子类通过重写覆盖父类的成员方法,即子类方法名,参数个数及类型和父类完全相同
	void message(double f,double s){
		setRate(f);
		super.setRate(s);
	}
}
public class lmw{
	public static void main(String[]args){
		LoanAccount lmw= new LoanAccount();
		lmw.message(3.14,5.28);
	}
}

6. If an interface area A illustrates one method area (),

    interface A {

       public double area();

    }

Please a triangular design implementation of the interface class A in GCLass area () method is a constructor parameter GClass trilateral length s1, s2, s3, are integers.

class GCLass implements A{
	public void area(int s1,int s2,int s3){
		double p,s;
		p=(s1+s2+s3)/2;
		s=Math.sqrt(p*(p-s1)*(p-s2)*(p-s3));
		System.out.println("area="+s);
	}
}
interface A {
    public double area();
}
public class lmw{
	public static void main(String[]args){
		GCLass s=new GCLass();
		s.area(3,4,5);
	}
}

7. The package has a mycolor class Color, wherein the method comprises a printColor (String color) can be specified by the parameter output string. Write a Java program, is introduced mycolor packet, and outputs the specified character string parameter used printColor method.

package mycolor;
public class color {
	public color(){	
	}
	public void printcolor(String color){
		System.out.println(color);
	}
}
import mycolor.color;
public class lmw {
	public static void main(String[] args) {
		color mine=new color();
		mine.printcolor("red");
	}
}

 

8. Use BufferedReader classes integer from receiving a keyboard and a real number, calculating their difference, and then output on the screen.

import java.io.*;
public class lmw {
	public static void main(String args[]) throws IOException {
		int i;
		float f, r;
		BufferedReader din = new BufferedReader(
				new InputStreamReader(System.in));
		System.out.print("input i: ");
		i = Integer.parseInt(din.readLine());
		System.out.print("input f: ");
		f = Float.parseFloat(din.readLine());
		r = i - f;
		System.out.println(i + "-" + f + "=" + r);
	}
}

 9. The program creates a Point class defines two variables in which coordinate values ​​of a point and then define constructor initializes the origin of coordinates and a defined way to achieve a moving point and then set the print method of the coordinates of the current point. And create an object verification.

class Point {
	int x, y;
	void move(int newX, int newY) {
		x = newX;
		y = newY;
	}
	void print() {
		System.out.println("x=" + x + " y=" + y);
	}
}
public class lmw {
	public static void main(String args[]) {
		Point p2;
		p2 = new Point();
		p2.print();
		p2.move(50, 50);
		System.out.println("**after moving**");
		p2.print();
	}
}

 10. Create a sequential file, the character part of the user's keyboard input to write to, and echoed to the screen.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;
public class lmw {
	private OutputStream outStream;
	private File f;
	public OutputStream getOStream(File f) {
		try {
			outStream = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("文件未找到");
			return null;
		}
		return outStream;
	}
	public static void main(String[] args) {
		lmw t = new lmw();
		File f = new File("c:/a.txt");
		OutputStream ostream = t.getOStream(f);
		Scanner sc = new Scanner(System.in);
		while (true) {
			try {
				String tmpString = sc.nextLine();
				if (tmpString != null) {
					System.out.println(tmpString);
					ostream.write(tmpString.getBytes());
				}
				if (tmpString.equals("exit")) {
					ostream.close();
					System.exit(0);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

11

 1. Programming to create a Box class, which defines three variables represented in length, width and height of a cube, and then define a method setDemo these three variables are initialized, and then define a method to calculate the volume of a cube. Create an object, to find the volume of a cube sized.

2. The method of the previous problem setDemo use the constructor to initialize achieved.

public class lmw {
	public static void main(String[] args) {
		Box l=new Box();
		l.setDemo(1,2,3);
		System.out.println(l.get());
	}
}
class Box{
	private double length,width,height;
	public void setDemo(double lenth,double width,double height)
	{
		this.length=lenth;
		this.width=width;
		this.height=height;
	}
	public double get(){
		return length*width*height;
	}
}
public class lmw{
public static void main(String[] args) {
		Box l;
		l=new Box(1,2,3);
		System.out.println(l.get());
	}
}
class Box{
	private double length,width,height;
	public Box(double lenth,double width,double height)
	{
		this.length=lenth;
		this.width=width;
		this.height=height;
	}
	public double get(){
		return length*width*height;
	}
}

12. Use Java Aplication of command line arguments reading two data, calculate the difference, and outputs the difference. If insufficient number of parameters, displays the appropriate message and exit the program execution.

public class lmw {
	public static void main(String[] args) {
		int i = 0, j = 0;
		if (args.length == 2) {
			i = Integer.valueOf(args[0]);
			j = Integer.valueOf(args[1]);
			System.out.println(i + "+" + j + "=" + (i + j));
		} else
			System.out.println("参数不足");
	}
}

13. Programming consists of two buttons and a label click event will take place text on the button to display the information in the label.

import java.awt.*;
import java.awt.event.*;
public class lmwjava implements ActionListener
{
	Frame fr;
	Panel pa;
	Button bt1,bt2;
	Label la;
lmwjava()
{
	fr=new Frame();
	pa=new Panel();
	bt1=new Button("Button 1");
	bt1.addActionListener(this);
	bt2=new Button("Button 2");
	bt2.addActionListener(this);
	la=new Label("显示文本信息:");
	pa.add(bt1);
	pa.add(bt2);
	fr.add(pa,"North");
	fr.add(la,"Center");
	fr.setVisible(true);
	fr.setSize(400,400);
}
	public void actionPerformed(ActionEvent e)
	{
		Object s=e.getSource();
		if(s==bt1)
			la.setText("Button 1");
		if(s==bt2)
			la.setText("Button 2");
	}
	public static void main(String[] args) {
		new lmwjava();
	}
}

 14. Programming includes a label and a button that, when clicked the button, the contents of the label between "hello" and "goodbye" to switch.

import java.awt.*;
import java.awt.event.*;
public class lmwjava extends Frame implements ActionListener 
//承Java的JFrame类,JFrame 是Java的窗体类,继承它可以重写它的一些方法达到更方便编程的作用
//implements ActionListener 是实现 ActionListener 接口,为动作监听接口,是Java swing 监听窗体动作的一个接口
{
	Panel cards;//Panel类也是一个容器,但是她不能单独存在只能存在于其他容器中,一个Panel对象代表了一个长方形区域这个区域可以容纳其他组件,在程序中通常会使用Panel来实现一个特殊的布局
	CardLayout Clayout = new CardLayout();// 定义卡片对象
	public lmwjava() 
	{
		Panel p = new Panel();
		Button bt = new Button("切换");
		bt.addActionListener(this);//这里必须有事件监听对象,并且this指本身这个对象,这个类会实现监听器这个接口
		p.add(bt);
		add("South", p);//把切换按钮添加到界面的南方
		
		cards = new Panel();
		cards.setLayout(Clayout);//设置当前页面布局
		
		Panel p1 = new Panel();
		p1.add(new Label("你好"));
		Panel p2 = new Panel();
		p2.add(new Label("再见"));
		
		cards.add("Panel with Label", p1);
		cards.add("Panel with Label", p2);
		add(cards);//把切换按钮添加到界面
	}
	public void actionPerformed(ActionEvent e)
//当特定于组件的动作(比如被按下)发生时,由组件(比如 Button)生成此高级别事件。事件被传递给每一个 ActionListener 对象,这些对象是使用组件的 addActionListener 方法注册的,用以接收这类事件。 
	{
		Clayout.next(cards);
	}
	public static void main(String args[]) {
		lmwjava window = new lmwjava();
		window.setTitle("转换");//添加界面主题
		window.pack();//依据放置的组件设定窗口的大小,使之正好能容纳放置的所有组件
		window.setVisible(true);//可以运行开始画图了
	}
}

 14. The program comprises a text box and a text area, when the content of the text box changed, the content of the text displayed in the text box in the region; press the Enter key, the clear text area in the text box.

import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Chanword extends Frame implements ActionListener,TextListener
{
	TextArea text;
	TextField input;
	Chanword(String s)
	{
		super(s);
		setLayout(new FlowLayout());
		input=new TextField(20);
		add(input);
		input.addActionListener(this);
		input.addTextListener(this);
		text=new TextArea(10,20);
		add(text);
		text.setEditable(false);
		setBounds(100,100,300,300);
		setVisible(true);
		validate();
	}
	public void actionPerformed(ActionEvent e)
	{
        text.setText(null);
	}
	public void textValueChanged(TextEvent e)
	{
		String sh=input.getText();
		text.append(sh);
	}
}
public class lmwjava
{
	public static void main(String argsp[])
	{
		Chanword change=new Chanword("修改");
	}
}

15. Use of InetAddress acquire an IP address of the host www.ytu.edu.cn; obtaining names and IP addresses of the local machine.

import java.net.InetAddress;
public class lmwjava {
	public static void main(String[] args) throws Exception {
		InetAddress localAddress = InetAddress.getLocalHost();
		InetAddress remoteAddress = InetAddress.getByName("www.ytu.edu.cn");
		System.out.println("本机的IP地址:" + localAddress.getHostAddress());
         System.out.println("本地的主机名:" + localAddress.getHostName());
		System.out.println("烟台大学的IP地址:" + remoteAddress.getHostAddress());
	}
}

16. A multi-threaded computing the summation from 1 to 100 

public class lmwjava {
    public static int sum = 0;
    public static Object LOCK = new Object();
    public static void main(String[] args) throws InterruptedException {
        lmwjava add = new lmwjava();
        ThreadTest thread1 = add.new ThreadTest(1, 25);
        ThreadTest thread2 = add.new ThreadTest(26, 50);
        ThreadTest thread3 = add.new ThreadTest(51, 75);
        ThreadTest thread4 = add.new ThreadTest(76, 100);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
 
         thread1.join();
         thread2.join();
         thread3.join();
         thread4.join();
         System.out.println("total result: "+sum);
    }
    class ThreadTest extends Thread {
        private int begin;
        private int end;
 
        @Override
        public void run() {
            synchronized (LOCK) {
                for (int i = begin; i <= end; i++) {
                    sum += i;
                }
                System.out.println("from "+Thread.currentThread().getName()+" sum="+sum);
            }
        }
 
        public ThreadTest(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }
    }
}

 

Guess you like

Origin blog.csdn.net/qq_43813697/article/details/89847787