Basic programming exercises for Java beginners

Posted by nickcwj on Wed, 05 Jan 2022 23:04:26 +0100

  1. The while loop and if statements are used to calculate and output the even sum of 1-100. The loop variable is named i and the stored variable is named sum.
    public class Test {
    	public static void main(String[] args) {
    		int sum=0,i=1;
    		while(i<=100)
    		{
    			if(i%2==0)
    			{
    				sum=sum+i;
    			}
    			i++;
    		}
    		System.out.println(sum);
    	}
    }

  2. The while loop and if statements are used to calculate and output the sum of 1-100 numbers that can be divided by 3. The loop variable is named i and the variable storing the sum is named sum.
    public class Test {
    	public static void main(String[] args) {
    		int sum=0,i=1;
    		while(i<=100)
    		{
    			if(i%3==0)
    			{
    				sum=sum+i;
    			}
    			i++;
    		}
    		System.out.println(sum);
    	}
    }

  3. Use the for loop and if statement to output a number from 1 to 100 that can be divided by 7 or the single digit is 7, and the loop variable is named i.
    public class Test {
    		public static void main(String[] args) {
    		int sum=0,i=1;
    		while(i<=100)
    		{
    			if(i%7==0 || i%10==7)
    			{
    				sum=sum+i;
    			}
    			i++;
    		}
    		System.out.println(sum);
    	}
    }

  4. Write an application program to calculate the factorial of integer n. The initial value of n is 8 and output the result. The cyclic variable is named i and the variable storing factorial is named p.
    public class test
    {	
    	public static void main(String[] args) {
    		int n=8,i=1,p=1;
    		i=n;
    		while(i>0)
    		{
    			p=p*i;
    			i--;
    		}
    		System.out.println(p);
    	}
    }

  5. The while loop and if statements are used to calculate and output the odd sum of 1-100. The loop variable is named i and the stored variable is named sum.
    public class Test {
    	public static void main(String[] args) {
    		int sum=0,i=1;
    		while(i<=100)
    		{
    			if(i%2==1)
    			{
    				sum=sum+i;
    			}
    			i++;
    		}
    		System.out.println(sum);
    	}
    }

  6. Suppose an employee's annual salary this year is 80000 yuan, and the annual salary growth rate is 6%. Write a Java application to calculate the employee's annual salary after 10 years and count the total income in the next 10 years (from this year). The cyclic variable is named i, and the total revenue variable is named total.
    public class Prog1{
    	public static void main(String[] args) {
    		int i;
    		double salary=80000,total=80000;
    		for(i=1;i<10;i++)
    		{
    			salary=salary*106/100;
    			total=total+salary;
    		}
    		System.out.println("10 years later,salary:"+salary);
    		System.out.println("10 years total:"+total);		
    	}
    }

  7. Create a Rectangle class and object. 1) Create a Rectangle class; 2) Attribute: two double member variables, width and height; 3) The construction method without parameters: the initial values of width and height are 6 and 8 respectively; 4) Method: calculate and output the perimeter of the Rectangle. The method name is findPremeter(); 5) Write a test class, create a Rectangle object named r, and call the perimeter and area methods.
    public class Rectangle
    {
    	private double width,height;
    	public Rectangle()
    	{
    		this.width=6;
    		this.height=8;
    	}
    	public double findPremeter()
    	{
    		return 2*(this.width+this.height);
    	}
    }
    
    
    public class Test
    {	
    	public static void main(String[] args) {
    		Rectangle r = new Rectangle();
    		System.out.println(r.findPremeter());
    	}
    }

  8. Create a class student whose attributes include peacetime score (pingshi) and final score (qimo); The construction method without parameters has the method of calculating and outputting the total score (). The calculation method is: total score = usual score + 1 / 2 of the final score; Create the test class, create the Student object s, and then call the calculateScore() method to output the total score.
    public class Student
    {
    	public int pingshi,qimo;
    	public Student(){}
    	public int calculateScore()
    	{
    		return pingshi+qimo/2;
    	}
    }
    
    
    public class Test
    {	
    	public static void main(String[] args) {
    		Student s = new Student();
    		s.pingshi=40;
    		s.qimo=50;
    		System.out.println(s.calculateScore());
    	}
    }

  9. Define the Circle class, including a construction method with the name of radius attribute and type of int without parameters and the method of calculating and outputting the area findArea (area = 3.14*radius*radius), write the test class, create an object c of the Circle class, and call the findArea method.
    class Circle
    {
    	public int radius;
    	public Circle(){}
    	public double findArea()
    	{
    		return radius*radius*3.14;
    	}
    }
    
    
    public class Test
    {	
    	public static void main(String[] args) {
    		Circle c = new Circle();
    	c.radius=2;
    		System.out.println(c.findArea());
    	}
    }

  10. Define a Book class to represent books. The attributes of this class include name (book name), author (author name) and price (book price). Define the construction method without parameters and the show method to output the basic information of books. Write a test class, create an object b of the book class, and call the show method.
    public class Book
    {
    	public String name,author;
    	public double price;
    	public Book(){}
    	public void show()	
    	{
    		System.out.println("name:"+this.name);
    		System.out.println("author:"+this.author);
    		System.out.println("price:"+this.price);
    	}
    }
    
    
    public class Test
    {	
    	public static void main(String[] args) {
    		Book b = new Book();
    b.name="Java Program";
    		b.author="panda";
    		b.price=3.14;
    		b.show();
    	}
    }

  11. Define a commodity class Goods, which has three attributes: commodity name (String), commodity number (String) and price (double), the construction method of whether there is a parameter and the method of calculating discount price. The method header is public void computeddiscount (double percent), where the formal parameter represents the percentage of discount. Write the test class, create the object of the commodity class, and call the method to calculate the discount price.
    public class Goods
    {
    public String name,number;
    			public double price;
    public Goods(){}
    public void computeDiscout(double percent)	
    {
    	System.out.println(price*percent/100);
    }
    }
    
    
    public class Test
    {	
    public static void main(String[] args) {
    	Goods g = new Goods();
    	g.name="Java Book";
    	g.number="G001";
    	g.price=3.14;
    	g.computeDiscout(90);
    }
    }
    

  12. The existing parent class Person has the following structure:
    class Person {
    	String id;
    	String name;
    
    	Person(String id, String name) {
    		this.id = id;
    		this.name = name;
    	}
    
    	void print() {
    		System.out.println("id =" + id + ",name =" + name);
    	}
    }
    On this basis, subclasses are derived Teacher,The subclass defines its own attribute teacher number( teacherID),
    There is a constructor without parameters, which overrides the of the parent class print Method to call the overridden of the parent class print method,
    Add a statement to print your own properties, please implement Teacher Class.
    class Teacher extends Person
    {
    private String teacherID;
    Teacher(){
    	super(null,null);
    }
    public void print()
    {
    	super.print();
    	System.out.println("teacherID:"+this.teacherID);
    }
    }

  13. The existing parent class Good has the following structure:
    class Goods {
    	double unitPrice;//Unit Price
    	double account;//quantity
    	Goods(double unitPrice, double account) {
    		this.unitPrice=unitPrice ;
    		this.account=account ;
    	}
    	double totalPrice() {//Calculate total price
    		return unitPrice * account;
    	}
    	void show() {
    		System.out.println("The unit price is" + unitPrice);
    		System.out.println("Purchase quantity is" + account);
    		System.out.println("The total amount of goods purchased is" + this.totalPrice());
    	}
    }
    On this basis, subclasses are derived Milk,The subclass defines its own attribute member price( vipPrice),
    There is a constructor without parameters, which overrides the of the parent class show Method to call the overridden of the parent class show method,
    Add a statement to print your own properties, please implement Milk Class.
    class Milk extends Goods
    {
    	private double vipPrice;
    	Milk()
    	{
    		super(0,0);
    	}
    	void show()
    	{
    		super.show();
    		System.out.println(this.vipPrice);
    	}
    }

  14. Write a program to simulate the "Challenge Cup" speech contest. A total of 10 judges score. The score is a random number between 1 and 10. Store the 10 scores in the int type array. Use the for loop to calculate the singer's final score.
    public class Test {
       public static void main(String[] args) {
    	 	int[] score = new int[10];
    		int max=1,min=10,avg=0,sum=0;
    		for(int i=0;i<10;i++)
    		{
    			score[i]=(int)(1+Math.random()*(10-1+1));
    			//System.out.println(score[i]);
    		}
    		for(int i=0;i<10;i++)
    		{
    			if(score[i]>max)
    				max=score[i];
    			if(score[i]<min)
    				min=score[i];
    			sum=sum+score[i];
    		}
    		avg=sum/10;
    
    	 System.out.println("max= "+max);//Highest score
    	 System.out.println("min= "+min);//Lowest score
    	 System.out.println("avg= "+avg);//average
    	}
    }

  15. An array a of int type is known. The array elements are {12,11,78,34}. The program uses the for loop to output the array in reverse order.
    public class Test {
    	public static void main(String[] args) {
    		int[] a = {12,11,78,34};
    		int i=a.length;
    		for(i=i-1;i>=0;i--)
    			System.out.print(a[i]);
    	}
    }

  16. Define a Boolean array with a length of 100, the array name is fig, and use the for loop statement to assign all elements of the array to false.
    public class Test {
    	public static void main(String[] args) {
    		int[] a = {34,56,78,89,90,100};
    		for(int i=0;i<a.length;i++)
    			System.out.print(a[i]/10%10);
    
       }
    }

  17. When a singer participates in the song Grand Prix, 20 judges score her and store it in an array score [], the score is a random number between 1 and 100. Programming uses the for loop to output the player's highest score, lowest score and final score (final score = total score / total number of judges)
    public class Test {
       public static void main(String[] args) {
    	 	int[] score = new int[20];
    		int max=1,min=100,avg=0,sum=0;
    		for(int i=0;i<20;i++)
    		{
    			score[i]=(int)(1+Math.random()*(100-1+1));
    			//System.out.println(score[i]);
    		}
    		for(int i=0;i<20;i++)
    		{
    			if(score[i]>max)
    				max=score[i];
    			if(score[i]<min)
    				min=score[i];
    			sum=sum+score[i];
    		}
    		avg=sum/20;
    
    	 System.out.println("max= "+max);//Highest score
    	 System.out.println("min= "+min);//Lowest score
    	 System.out.println("avg= "+avg);//average
    	}
    }

  18. The following are Name class, Person class and Test class. Please complete the accessor methods of all private data fields in Name class and Person class.

    class Name
    {
    	private String firstName;//surname
    	private String lastName;//name
    	Name(String f,String l)
    	{
    		firstName=f;
    		lastName=l;
    	}
    	//Fill in accessor method
    	public String toString()
    	{
    		return firstName + lastName;
    	}
    }
    class Person
    {
    	private Name name;//full name
    	Person(Name n)
    	{
    		name=n;
    	}
    //Fill in accessor method
    }
    class Test
    {
    	public static void main(String[] args)
    	{
    		Name theName=new Name("Zhang","three");
    		Person p=new Person(theName);
    		System.out.println(p.getName());//Output result: Zhang San
    	}
    }
    class Name
    {
    	private String firstName;//surname
    	private String lastName;//name
    	Name(String f,String l)
    	{
    		firstName=f;
    		lastName=l;
    	}
    	public String getFirstName()
    	{
    		return firstName;
    	}
    	public void setFirstName(String fn)
    	{
    		firstName=fn;
    	}
    	public String getLastName()
    	{
    		return lastName;
    	}
    	public void setLastName(String ln)
    	{
    		lastName=ln;
    	}
    	public String toString()
    	{
    		return firstName + lastName;
    	}
    	
    }
    class Person
    {
    	private Name name;//full name
    	Person(Name n)
    	{
    		name=n;
    	}
    	public Name getName()
    	{
    		return name;
    	}  
    	public void setName(Name n)
    	{
    		name=n;
    	}
    }
    class Test
    {
    	public static void main(String[] args)
    	{
    		Name theName=new Name("Zhang","three");
    		Person p=new Person(theName);
    		System.out.println(p.getName());//Output result: Zhang San
    	}
    }

 

Topics: Java Back-end