JAVA basic exercise (HOW2J.CN)

@TOC

JAVA basic exercise (HOW2J.CN)

Exercise - naming conventions

Consider whether the following variable names are legal. If not, why?

1. int a_;
2. int a@;
3. int a3;
4. int 8@;
5. int 9_;
6. int X$_;
7. int y;
8. int _$_;
9. int $_$;
10. int $*$;
11. int $1$;
12. int _1_;
13. int _@_;
14. int a#;
15. int a";
16. int 123a";
17. int 123a_;
18. int $123b_;

Exercise - naming convention answers

1. Right

2. Error '@' cannot be used as a variable name

3. Right

4. Error "@" cannot be used as a variable name. The first one cannot be a number

5. Wrong. The first one cannot be a number

6. Right

7. Right

8. Right

9. Right

10. Error '*' cannot be used as variable name

11. Right

12. Right

13. Error '@' cannot be used as a variable name

14. Error '#' cannot be used as variable name

15. Error '' '' cannot be used as a variable name / / the beginning cannot be a number

16. Error '' '' cannot be used as a variable name / / the beginning cannot be a number

17. Wrong beginning cannot be a number

18. Right

Exercise - scope

The scope of the attribute is in the method, and the scope of the parameter is also in the method. If the name of the attribute and the parameter are the same? So what is the value?

public class HelloWorld {
    int i = 1; //The attribute name is i
    public void method1(int i){ //The parameter is also i
        System.out.println(i); 
    }
public static void main(String[] args) {
	new HelloWorld().method1(5);
	//Is the result printed 1 or 5?
	}
}

Exercise - scope answers

Output results:

5

Exercise final

If final modifies a parameter, can you assign a value to this parameter in the method?

public class HelloWorld {    
	public void method1(final int j) {
		j = 5; //Can this be implemented?
	}
}

Exercise - final answer

No, it can't be executed.

① This variable has been modified by final. Once a method passes in a parameter, it is equivalent to assignment, and future assignment cannot be performed.

② J has been assigned by 5. final int j needs to pass in parameters, so it is assigned again.

Exercise - summation

use Scanner Get two numbers from the console and calculate the sum of the two numbers

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-grqsddk-1627779684832) (C: \ users \ 86133 \ desktop \ 2141. PNG)]

Exercise - summation answer

public static void main(String[] args) {
	Scanner s =	new	Scanner(System.in);
	int a = s.nextInt();
	System.out.println("First integer:"+a);
	int b = s.nextInt();
	System.out.println("Second integer:"+b);
	System.out.println("The sum of the two numbers is:"+(a+b));
}

Practice - self increasing

int i =1;

int j = ++i + i++ + ++i + ++i + i++;

Exercise - self increasing answers

int i =1;

int j = ++i + i++ + ++i + ++i + i++;

​ 2 + 2 + 4 + 5 + 5 =18

Exercise - BMI

use Scanner Collect your height and weight and calculate your BMI

BMI is calculated as weight (kg) / (height * height)

For example, Qiu Yangbo's weight is 72kg and his height is 1.69, so the student's BMI is
72 / (1.69*1.69) = ?

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-QguZpAHy-1627779684835)(C:\Users133\Desktop55.png)]

Exercise - BMI answers

public static void main(String[] args) {
	double BMI;
	Scanner s = new Scanner(System.in);
	System.out.println("Please enter your height( m): ");
	double height = s.nextFloat();
	System.out.println("Please enter your weight( kg): ");
	double  weight = s.nextFloat();
	BMI	=	weight/(height*height);
	System.out.println("Current BMI Yes:"+BMI);
	
	if(BMI<18.5) {
		System.out.println("Underweight");
	}
	else if(BMI >=18.5 && BMI<24) {
		System.out.println("normal range ");
	}
	else if(BMI >=24 && BMI<27) {
		System.out.println("Overweight");
	}
	else if(BMI >=27 && BMI<30) {
		System.out.println("Mild obesity");
	}
	else if(BMI >=30 && BMI<35) {
		System.out.println("Moderate obesity ");
	}
	else if(BMI >=35) {
		System.out.println("Severe obesity");
	}
}

Exercise - relational operators

With the help of Scanner Get two arbitrary numbers entered by the console, and then use
>Greater than
>=Greater than or equal to
< less than
< = less than or equal to
==Are they equal
!= Whether unequal

Judge the relationship between two values

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-JFk99DVn-1627779684837)(C:\Users133\Desktop47.png)]

Exercise - relational operator answers

public static void main(String[] args) {
	Scanner s =	new Scanner(System.in);
	int a = s.nextInt();
	System.out.println("First integer:"+a);
	int b = s.nextInt();
	System.out.println("Second integer:"+b);
	
	System.out.print("compare"+a+">"+b+": ");
	if(a>b) 
	{
		System.out.println("true");
	}
	else {
		System.out.println("false");
	}
	
	System.out.print("compare"+a+">="+b+": ");
	if(a>=b) 
	{
		System.out.println("true");
	}
	else {
		System.out.println("false");
	}
	
	System.out.print("compare"+a+"<"+b+": ");
	if(a<b) 
	{
		System.out.println("true");
	}
	else {
		System.out.println("false");
	}
	
	System.out.print("compare"+a+"<="+b+": ");
	if(a<=b) 
	{
		System.out.println("true");
	}
	else {
		System.out.println("false");
	}
	
	System.out.print("compare"+a+"=="+b+": ");
	if(a==b) 
	{
		System.out.println("true");
	}
	else {
		System.out.println("false");
	}
	
	System.out.print("compare"+a+"!="+b+": ");
	if(a!=b) 
	{
		System.out.println("true");
	}
	else {
		System.out.println("false");
	}
}

Exercise - logical operators

int i = 1;

boolean b = !(i++ == 3) ^ (i++ ==2) && (i++==3);

System.out.println(b);

System.out.println(i);

What is the output?

Exercise - logical operator answers

boolean b =!(i++ == 3) ^ (i++ ==2) && (i++==3);

​ =! ( 1 == 3 ) ^ ( 2 == 2 ) && ( 3 == 3)

​ = true^true&&false

​ = false&&false

​ =false

! (i++==3) take the value first and then operate. If i + + is 1, it is not equal to 3. If false is taken as true, i=2

(i++ ==2) take the value first and then operate. i + + is 2. 2 is equal to 2. True and true XOR are the same as false. At this time, i=3

i++==3 value before operation i + + is 3 3 equals 3 true false and true is false

Because the short circuit and i++==3 after the front is flash do not operate, i is still 3 at this time

Output results

false

3

Exercise - quick calculation 2x16

2x16 is calculated without the multiplication symbol (*)

Exercise - quickly calculate 2x16 answers

public static void main(String[] args) {
	System.out.println(16<<1);
}

Exercise - bitwise operators

int i = 3; // Binary is 11

int j = 2; // Binary is 10

int c = ((i | j) ^ (i & j)) << 2 >>> 1;

Mental arithmetic answer

Exercise - bitwise operator answers

int c = ((i | j) ^ (i & j)) << 2 >>> 1;

​ = 011 | 010 = 011 ^ 011 & 010 = 010

	   =                               001     <<2 >>>1     

​ = 100 >>>1

​ = 010

2

Exercise - assignment operators

int i = 1;

i+=++i;

Exercise - assignment operator answers

3

Exercise - determine if it is a working day

adopt Scanner Enter an integer between 1 and 7, and use the ternary operator to determine whether it is a weekday or weekend?

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-DA3nIsRJ-1627779684840)(C:\Users133\Desktop54.png)]

Exercise - determine if it's a weekday answer

public static void main(String[] args) {
	Scanner s = new Scanner(System.in);
	System.out.println("What day is it today?");
	int date = s.nextInt();
	String massage = date < 6 ? "Today is a working day": "Today is the weekend";
	System.out.println(massage);
}

Practice - leap year

Judge whether a year is a leap year
adopt Scanner Enter a year and judge whether it is a leap year

Leap year judgment criteria (meet any one)
\1. If it can be divided by 4, but it cannot be divided by 100
\2. Can be divided by 400

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-f3XWqPVp-1627779684841)(C:\Users133\Desktop66.png)]

Exercise - leap year answers

public static void main(String[] args) {
	Scanner s = new Scanner(System.in);
	int year = s.nextInt();
	if(year % 4 == 0 && year % 100 !=0 ) {
		System.out.println(year+"It's a leap year");
	}
	else if(year % 400 == 0) {
		System.out.println(year+"It's a leap year");
	}
	else {
		System.out.println(year+"Not a leap year");
	}
}

Exercise - Season

adopt Scanner Enter the month and use switch to determine the season

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-00k2BIVg-1627779684842)(C:\Users133\Desktop68.png)]

Exercise - Seasonal answers

public static void main(String[] args) {
	Scanner s = new Scanner(System.in);
	System.out.println("Please enter the month");
	int month = s.nextInt();
	switch(month) {
	case 1:
	case 2:
	case 3:
		System.out.println("spring");
		break;
	case 4:
	case 5:
	case 6:
		System.out.println("summer");
		break;			
		
	case 7:
	case 8:		
	case 9:
		System.out.println("autumn");
		break;			

	case 10:
	case 11:
	case 12:		
		System.out.println("winter");
		break;			

	}
}

Exercise - factorial

adopt Scanner Get an integer, and then use while to calculate the factorial of the integer

The factorial of N is equal to N* (N-1) * (N-2) *... * 1

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-maSglozH-1627779684843)(C:\Users133\Desktop70.png)]

Exercise - factorial answers

public static void main(String[] args) {
	Scanner s = new Scanner(System.in);
	System.out.println("Please enter an integer:");
	int num = s.nextInt();
	int i=1;
	int result=1;
	while(i<=num) {
		result *=i;
		i++;
	}
	System.out.println("The factorial is:"+result);
}

Practice - beggar

There was a beggar named Hong in the Chinese dynasty. He went to the overpass to ask for money
I asked for 1 yuan on the first day
I asked for 2 yuan the next day
I asked for four dollars on the third day
Eight dollars on the fourth day
and so on

Question: how much does beggar Hong earn after working for 10 days?

Practice - beggar answer

static int inCome(int day,int income) {
	for(int i = 1; i<=day-1;i++) {
		income=income*2;
	}
	return income;
}

public static void main(String[] args) {
	int income = 1;
	int summy = 0;
	for(int day=1;day<=10;day++) {
		summy +=income;
		income = inCome(day,2);
	}
	System.out.println(summy);
}

1023

Exercise - ignore multiples

Print the number between 1 and 100. If the number is either a multiple of 3 or 5, ignore it

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Uzt3KIRh-1627779684843)(C:\Users133\Desktop76.png)]

Exercise - ignore multiple answers

public static void main(String[] args) {
	for(int i=1;i<=100;i++) {
		if(i%3==0 || i%5==0) {
			continue;
		}
		System.out.println(i);
	}
}

Exercise - golden section point

Find the division of two numbers, and the result is closest to the golden section point of 0.618

Denominator and numerator cannot be even at the same time
The denominator and numerator values range from [1-20]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Viufg1gs-1627779684845)(C:\Users133\Desktop78.png)]

Exercise - golden section point answer

	public static void main(String[] args) {
		float demominator	=	0;	//denominator
		float member	=	0;	//molecule
		float closer	=	0;	//Recent answers
		float result	=	0;
		float outputresult  = 0;
		float i,j;
		
		
		for(i=1;i<=20;i++) {
			for(j=1;j<=20;j++) {
				result = j	/	i;
				
				if(result>closer && result<0.618) {
					closer=result;
					member = j;
					demominator	=	i;
				}
			}
		}
		outputresult = member / demominator;
		System.out.print("From golden section point (0).618)The last two numbers are divided by:"+member+"/"+demominator+"="+outputresult);
	}

Exercise - daffodils count

Definition of daffodils:
\1. It must be three digits
\2. The cube of each bit adds up to the number itself, such as 153 = 111 + 555 + 333

Look for all the daffodils

Exercise - daffodils number answer

public static void main(String[] args) {
	int sum;
	for(int i=1;i<=9;i++) {
		for(int j = 0;j<=9;j++) {
			for(int k = 0;k<=9;k++) {
				sum=i*100+j*10+k;
				if(sum==i*i*i+j*j*j+k*k*k) {
					System.out.println(sum);
				}
			}
		}
	}
}

Exercise - primary school arithmetic problems

Prompt to use multi-level loop nesting to solve

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-mImISivc-1627779684846)(C:\Users133\Desktop34.png)]

Exercise - primary school arithmetic answers

public static void main(String[] args) {
	int a,b,c,d;
	for(a=0;a<100;a++) {
		for(b=0;b<100;b++) {
			for(c=0;c<100;c++) {
				for(d=0;d<100;d++) {
					if(a+b==8 && a+c==14 && b+d==10 &&c-d==6) {
						System.out.println("a="+a+",b="+b+",c="+c+",d="+d);
					}
				}
			}
		}
	}
}

Exercise - array minimum

First create an array with a length of 5
Then give each bit of the array a random integer
Through the for loop, traverse the array to find the smallest value

There are many ways to obtain random integers from 0 to 100. The following is one of the reference methods:

(int) (Math.random() * 100)

Math.random() will get a random floating-point number between 0 and 1, multiply it by 100, and force it into an integer.

public class HelloWorld {
	public static void main(String[] args) {
		int[] a = new int[5];
		a[0] = (int) (Math.random() * 100);
		a[1] = (int) (Math.random() * 100);
		a[2] = (int) (Math.random() * 100);
		a[3] = (int) (Math.random() * 100);
		a[4] = (int) (Math.random() * 100);
		
		System.out.println("Each random number in the array is:");
		for (int i = 0; i < a.length; i++) 
			System.out.println(a[i]);
		
		System.out.println("The purpose of this exercise is to find the smallest value: ");
	}
}

Exercise - array minimum answer

public static void main(String[] args) {
	int []a = new int[5];
	a[0] = (int) (Math.random() * 100);
	a[1] = (int) (Math.random() * 100);
	a[2] = (int) (Math.random() * 100);
	a[3] = (int) (Math.random() * 100);
	a[4] = (int) (Math.random() * 100);
	
	System.out.println("Each random number in the array is:");
	for (int i = 0; i < a.length; i++) 
		System.out.println(a[i]);
	
	int min=a[0];
	for(int i =1;i<5;i++) {
		if(min>a[i]) {
			min=a[i];
		}
	}
	System.out.println("The minimum value of this array is:"+min);
}

Keywords: Java Eclipse

Added by kodlcan on Mon, 03 Jan 2022 21:25:20 +0200