Basic Java Exercises

import java.util.Scanner;

public class T1 {
	public static void main(String[] args) {
		// Enter a number to determine if it is a prime number

		// Ideas: For example, if the user input is 36, we can try to divide it, using a loop, from 2 to 35

		System.out.println("Please enter a number. Determine whether it is a prime number");
		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt();
		boolean flag = true;

		for (int i = 2; i < num; i++) {
			if (num % i == 0) {
				flag = false;
				break;
			}
		}
		if (flag) {
			System.out.println(num + "is a prime number");
		} else {
			System.out.println(num + "not prime");
		}
	}
}




import java.util.Scanner;

public class Practice {
	public static void main(String[] args) {
		//Use a loop to print the following Christmas tree
		// Let the user enter the height of the tree
//			*
//		   ***
//		  *****
//		 *******
//		*********
		
		//law:
		//Number of stars = 2*n(n is the current line number)-1
		//space = (h is the height of the Christmas tree) hn (n is the current line number)
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Please enter the number of lines. Output Christmas tree");
		int height = scanner.nextInt();
		
		for (int i = 1; i <= height; i++) {
			// first output the space, i is the current line number
			for (int j = 1; j <= height-i; j++) {
				System.out.print(" ");
			}
			//Output stars, the number of stars in each row is 2*n (n is the current row number)-1
			for (int k = 1; k <= 2*i-1; k++) {
				System.out.print("*");
			}
			// output is complete, newline
			System.out.println();
		}
	}
}




public class Practice2 {
	public static void main(String[] args) {
		// A hundred dollars and a hundred chickens
		// 5 pieces for a rooster, 3 pieces for a hen, 1 piece for three chicks, ask 100 pieces to buy 100 chickens
		// How many Chinese buys are there?

		int cock; // cock
		int hen; // hen
		int chick;// chick

		for (cock = 0; cock <= 20; cock++) {
			for (hen = 0; hen <= 33; hen++) {
				for (chick = 0; chick <= 100; chick++) {

					if (chick % 3 == 0) { //Three chicks 1 piece
						if ((cock + hen + chick == 100) && (cock * 5 + hen * 3 + chick / 3 == 100)) {
							System.out.println("cock has:" + cock + "only" + "hen has:" + hen + "only" + "chick has:" + chick + "only");
						}
					}
				}
			}
		}
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327019830&siteId=291194637