Programming
Introduction
public class Main {
public static void main(String[] args) {
System.out.print("Hello, world!");
System.out.print("Another, world!\n");
System.out.println("Knock, knock");
}
}
Data Types
int x = 123;
double y = 1.2;
boolean z = true;
char symbol = '@';
String text = "Rangas";
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(symbol);
System.out.println("Hello " + symbol + text);
Exercise
String x = "Water";
String y = "Cola";
String temp; // String temp = null;
temp = x;
x = y;
y = temp;
System.out.println("x: " + x);
System.out.println("y: " + y);
Input Issue
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is your name?");
String name = scanner.nextLine();
System.out.println("How old are you?");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("What is your fav food?");
String food = scanner.nextLine();
scanner.close();
System.out.println("Hello " + name + ".");
System.out.println("Your are " + age + " year old.");
System.out.println("Your like " + food + ".");
}
}
Note
int friends = 10;
//friends = friends + 1; (or) friends++;
System.out.println(friends);
Dialog
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog("Enter your name");
JOptionPane.showMessageDialog(null, "Hello " + name);
int age = Integer.parseInt(JOptionPane.showInputDialog("Enter your age"));
JOptionPane.showMessageDialog(null, "Your age is " + age + " year old");
double height = Double.parseDouble(JOptionPane.showInputDialog("Enter your height"));
JOptionPane.showMessageDialog(null, "Your height is " + height);
}
}
Math
double x = 3.14;
double y = -10;
double z = Math.min(x, y); // max
System.out.println(z);
double y2 = -10;
double z2 = Math.abs(y2); // without negative sign
System.out.println(z2);
double y3 = 10;
double z3 = Math.sqrt(y3); // square root with decimal
System.out.println(z3);
double x2 = 3.14;
double z4 = Math.round(x2); // real world calculation
//double z4 = Math.ceil(x2); // up
//double z4 = Math.floor(x2); // down
System.out.println(z4);
Exercise
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double x, y, z;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
x = scanner.nextDouble();
System.out.print("Enter second number: ");
y = scanner.nextDouble();
z = Math.sqrt((x * x) + (y * y));
System.out.println(z);
scanner.close();
}
}
Logical Operator
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Logical operator - &&, ||, !
Scanner scanner = new Scanner(System.in);
System.out.print("q or Q : ");
String response = scanner.nextLine();
if (response.equals("q") || response.equals("Q")) {
System.out.println("Bye");
} else {
System.out.println("Good");
}
}
}
if else, if else if
int age = 17;
if(age >= 75) {
System.out.println("Ok Boomer.");
}
else if (age >= 18) {
System.out.println("You are an adult.");
}
else {
System.out.println("You are not adult");
}
Exercise
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String name;
int age;
boolean student;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
name = scanner.nextLine();
System.out.print("Enter your age: ");
age = scanner.nextInt();
scanner.nextLine();
System.out.print("Are you student? true/false: ");
student = scanner.nextBoolean();
if (name.isEmpty()) {
System.out.println("Name error.");
}
else {
System.out.println("Hello " + name);
}
if (age < 1) {
System.out.println("Age Error.");
}
else if (age <= 16) {
System.out.println("age 1-16");
}
else if (age <= 60) {
System.out.println("age 17-60");
}
else if (age > 60) {
System.out.println("age 60+");
}
else {
System.out.println("Age type Error");
}
if (student) {
System.out.println("Your are Student.");
}
else {
System.out.println("Your are not Student.");
}
}
}
Random
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
//int x = random.nextInt(); // + & -
//int x = random.nextInt(6); // 0 to 6
int x = random.nextInt(6) + 1; // 1 to 6
double y = random.nextDouble(); // between 0 & 1
boolean z = random.nextBoolean();
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}
Exercise
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
boolean myBoo;
myBoo = random.nextBoolean();
if (myBoo) {
System.out.println("Hard");
}
else {
System.out.println("Tail");
}
}
}
printf()
a method used to format output %[flags][width][.precision][specifier-character]
String name = "DJ Rangas";
char firstLetter = 'R';
int age = 24;
double height = 24.9;
boolean work = true;
System.out.printf("String - %s\n", name);
System.out.printf("Character - %c\n", firstLetter);
System.out.printf("Integer - %d\n", age);
System.out.printf("Double - %f\n", height);
System.out.printf("Boolean - %b\n", work);
System.out.printf("String - %s & Integer - %d\n", name, age);
double num1 = 100.1;
double num2 = 3330000.145;
double num3 = -9900.87;
// 6 decimal auto
System.out.printf("%f\n", num1);
System.out.printf("%f\n", num2);
System.out.printf("%f\n", num3);
// + = output a plus
// , = comma grouping separator
// (= negative numbers are enclosed in ()
// space = display a minus if negative, space if positive
// adjust decimal
System.out.printf("%.2f\n", num1);
System.out.printf("%.2f\n", num2);
System.out.printf("%.2f\n", num3);
System.out.printf("%+.2f\n", num1);
System.out.printf("%+.2f\n", num2);
System.out.printf("%+.2f\n", num3);
System.out.printf("%,.2f\n", num1);
System.out.printf("%,.2f\n", num2);
System.out.printf("%,.2f\n", num3);
System.out.printf("%(.2f\n", num1);
System.out.printf("%(.2f\n", num2);
System.out.printf("%(.2f\n", num3);
System.out.printf("% .2f\n", num1);
System.out.printf("% .2f\n", num2);
System.out.printf("% .2f\n", num3);
// 0 = zero padding
// number = right justified padding
// negative number = left justified padding
int id1 = 1;
int id2 = 23;
int id3 = 456;
int id4 = 7890;
System.out.printf("%4d\n", id1);
System.out.printf("%4d\n", id2);
System.out.printf("%04d\n", id3);
System.out.printf("%-4d\n", id3);
System.out.printf("%d\n", id4);
double principal;
double rate;
int timesCompounded;
int years;
double amount;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the principal amount: ");
principal = scanner.nextDouble();
System.out.print("Enter the interest rate (in %): ");
rate = scanner.nextDouble() / 100;
System.out.print("Enter the # of times compounded per year: ");
timesCompounded = scanner.nextInt();
System.out.print("Enter the # of years: ");
years = scanner.nextInt();
amount = principal * Math.pow(1 + rate / timesCompounded, timesCompounded * years);
System.out.printf("The amount after %d years is $%,.2f", years, amount);
Netshed if
boolean isStudent = false;
boolean isSenior = true;
double price = 9.99;
if (isStudent) {
if (isSenior) {
System.out.println("Student discount 10%");
System.out.println("Senior discount 20%");
price *= 0.7;
}
else {
System.out.println("Student discount 10%");
price *= 0.9;
}
}
else {
if (isSenior) {
System.out.println("Senior discount 20%");
price *= 0.8;
}
else {
price *= 1;
}
}
System.out.printf("Balance = %.2f", price);
String
String name = "DJ Rangas";
int intNum = name.length(); // Start 1
char charNum = name.charAt(0); // Start 0
int index = name.indexOf("a"); // Start 0
int lastIndex = name.lastIndexOf("a"); // Start 0
System.out.println(intNum);
System.out.println(charNum);
System.out.println(index);
System.out.println(lastIndex);
System.out.println(name.toUpperCase());
System.out.println(name.toLowerCase());
String name2 = " DJ Rangas ";
System.out.println(name2.trim());
System.out.println(name2.isEmpty());
System.out.println(name2.contains(" "));
System.out.println(name2.equals(" DJ Rangas "));
System.out.println(name2.equalsIgnoreCase(" dj Rangas "));
System.out.println(name.replace("a", "u"));
.substring
// A method used to extract a portion of a string
//.substring(start, end)
//.substring(start)
String email = "djrangas21@gmail.com";
String username = email.substring(0, 10);
String domain = email.substring(11);
String usernameAdv = email.substring(0, email.indexOf("@"));
String domainAdv = email.substring(email.indexOf("@") + 1);
System.out.println(username);
System.out.println(domain);
System.out.println(usernameAdv);
System.out.println(domainAdv);
Exercise
String email;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your Email: ");
email = scanner.nextLine();
if (email.contains("@")) {
System.out.println("name - " + email.substring(0, email.indexOf("@")));
System.out.println("domain - " + email.substring(email.indexOf("@") + 1));
}
else {
System.out.println("Email error");
}
Exercise
Scanner scanner = new Scanner(System.in);
double weightLb, weightKg;
int choice;
System.out.println("Weight Conversion Program");
System.out.println("1: Convert lbs to kgs");
System.out.println("2: Convert kgs to lbs");
System.out.print("Choose an option: ");
choice = scanner.nextInt();
if (choice == 1) {
System.out.print("Enter the weight in lbs: ");
weightLb = scanner.nextDouble();
weightKg = weightLb * 0.453592;
System.out.printf("kgs: %.2f", weightKg);
}
else if (choice == 2) {
System.out.print("Enter the weight in kgs: ");
weightKg = scanner.nextDouble();
weightLb = weightKg / 0.453592;
System.out.printf("lbs: %.2f", weightLb);
}
else {
System.out.println("Error");
}
ternary operator ?
// Return 1 of 2 values if a condition is true
// variable = (condition) ? ifTrue : ifFalse;
int Score = 50;
String passOrFail = (Score > 60) ? "Pass" : "Fail";
System.out.println(passOrFail);
Exercise
Scanner scanner = new Scanner(System.in);
double temp, newtemp;
String unit;
System.out.print("Enter a temperature: ");
temp = scanner.nextDouble();
scanner.nextLine();
System.out.print("Unit C or F: ");
unit = scanner.nextLine().toUpperCase();
newtemp = (unit.equals("C")) ? (temp - 32) * 5 / 9 : (temp * 5 / 9) + 32;
System.out.printf("%.2f° %s", newtemp, unit);
switch
String day = "Friday";
switch (day) {
case "Sunday" -> System.out.println("Today is Sunday");
case "Monday" -> System.out.println("Today is Monday");
case "Tueday" -> System.out.println("Today is Tueday");
case "Wednesday" -> System.out.println("Today is Wednesday");
case "Thursday" -> System.out.println("Today is Thursday");
case "Friday", "Saturday" -> System.out.println("Today is Friday or Saturday");
default -> System.out.println("Today is not Luckyday");
}
String day = "Gym";
switch (day) {
case "Sunday":
System.out.println("Today is Sunday");
break; // should test without break
case "Monday":
System.out.println("Today is Monday");
break;
case "Tueday":
System.out.println("Today is Tueday");
break;
case "Wednesday":
System.out.println("Today is Wednesday");
break;
case "Thursday":
System.out.println("Today is Thursday");
break;
case "Friday":
System.out.println("Today is Friday");
break;
case "Saturday":
System.out.println("Today is Saturday");
break;
default:
System.out.println("Today is not Luckyday");
}
Last updated