Brute Force Techniques I
This is a descriptionLeap Year
import java.util.Scanner;
public class LeapYear {
public static boolean isLeap(int year) {
if (year % 4 != 0) {
return false;
} else if (year % 100 != 0) {
return true;
} else if (year % 400 != 0) {
return false;
} else {
return true;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the year: ");
int year = scanner.nextInt();
System.out.println("Is it a leap year? " + isLeap(year));
}
}
Implicit & Explicit Conversion
import java.util.Scanner;
public class DataConversion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the integer: ");
int integer = scanner.nextInt();
System.out.println("Enter the double: ");
double doubler = scanner.nextDouble();
System.out.println("Enter the character: ");
char character = scanner.next().charAt(0);
System.out.println("int to byte: " + (byte)integer);
System.out.println("char to int: " + (int)character);
System.out.println("double to byte: " + (byte)doubler);
System.out.println("double to int: " + (int)doubler);
}
}
Bitwise Operation (by 2)
import java.util.Scanner;
public class BitwiseOperation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = scanner.nextInt();
System.out.println("The division is " + (num >> 1));
System.out.println("The multiplication is " + (num << 1));
}
}
“Observe & Analyze”
(This is supposed to give an error for lossy data conversion.)
public class ObserveAnalyze {
public static void main(String[] args) {
int a = 10;
double b = a;
System.out.println("1. implicit int to double: " + b);
double c = 10.5;
int d = c;
System.out.println("2. implicit double to int: " + d);
double e = 10.5;
int f = (int) e;
System.out.println("3. explicit double to int:" + f);
}
}
Four-Function Calculator
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String choice = null;
do {
System.out.println("Enter first number, operator, second number: ");
String operation = scanner.nextLine();
String[] operationList = operation.split(" ");
int firstNum = Integer.parseInt(operationList[0]);
int secondNum = Integer.parseInt(operationList[2]);
switch (operationList[1]) {
case "+":
System.out.println("Answer is: " + (firstNum + secondNum));
break;
case "-":
System.out.println("Answer is: " + (firstNum - secondNum));
break;
case "*":
System.out.println("Answer is: " + (firstNum * secondNum));
break;
case "/":
System.out.println("Answer is: " + (firstNum / secondNum));
break;
default:
System.out.println("Invalid input.");
}
System.out.println("Do you want to continue? [y/N]");
choice = scanner.nextLine();
} while (choice.equals("y"));
}
}