-
- Simple Java code snippets
Calculating circumference of a circle
package circumference;
import java.util.Scanner;
/**
* Uses Java Math library
* @author azmeer
*/
public class Circumference {
public static void main(String[] args) {
System.out.println("Calculate the circumference of a circle - with user input");
Scanner in = new Scanner(System.in);
int r;
double c;
System.out.print("What is the radius? ");
r = in.nextInt();
c = 2 * Math.PI * r;
System.out.println("pi=" + Math.PI);
System.out.println("radius=" + r + " circumference=" + c);
}
}
Odd/Even detector with modulo operator
import java.util.Scanner;
/**
* Using modulo operator
* @author azmeer
*/
public class OddEven {
public static void main(String[] args) {
int n, x;
System.out.println("Odd/Even detector");
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number: ");
n = in.nextInt();
x = n % 2;
if (x == 0) {
System.out.println(n + " is an even number");
} else {
System.out.println(n + " is an odd number");
}
}
}
Age calculator
If the age is less than 18, then the person is a child
import java.util.Scanner;
/**
* Calculate age with given year of birth value
*
* @author azmeer
*/
public class CalcAge {
public static void main(String[] args) {
System.out.println("Age Calculator");
Scanner in = new Scanner(System.in);
int age, yob;
System.out.print("What is your year of birth? ");
yob = in.nextInt();
age = 2023 - yob;
System.out.println("You are " + age + " years old");
if (age < 18) {
System.out.println("You are a child");
} else {
System.out.println("You are an adult");
}
}
}