Code Samples
This page contains the code we did in class and other similar examples. Follow this page as a reference. Codes for recent labs will be at the beginning.
Always remember to save your java file with same name as that of the class name that you have declared.
Hello World
public class HelloWorld{
public static void main(String args[]){
System.out.println("Hello World");
}
}
SimpleAddition
import java.util.Scanner;
public class SimpleAddition{
public static void main(String[] args){
//declaration of results variable as integer type
int result;
// create a scanner object of name inputScanner to read input.
Scanner inputScanner = new Scanner(System.in);
//reads input, treat it as an integer value and saves it in x and y variable.
//declaration and initialization
int x = inputScanner.nextInt();
int y = inputScanner.nextInt();
//add x and y ; save it in another varaible result
result = x + y;
//print the value stored in result variable in the terminal
System.out.println(result);
}
}
FahrenheitToCelsius
import java.util.Scanner;
public class FahrenheitToCelsius{
public static void main(String[] args){
Scanner sc_object = new Scanner(System.in); // create scanner object
double fahrenheit = sc_object.nextDouble(); //declare and initialize user input as double value// other methods such as next() ; nextInt() ; nextDouble()
double celsius = ( fahrenheit - 32) * (5.0/9.0);
System.out.println(celsius);
}
}
BouncerBot
import java.util.Scanner;
public class BouncerBot{
public static void main(String[] args){
Scanner sc_object = new Scanner(System.in);
//First 3 inputs as current month, day and year
int thisMonth = sc_object.nextInt();
int thisDay = sc_object.nextInt();
int thisYear = sc_object.nextInt();
// remaining 3 inputs as birth month, day and year
int birthMonth = sc_object.nextInt();
int birthDay = sc_object.nextInt();
int birthYear = sc_object.nextInt();
boolean isBday = (thisDay == birthDay) && (thisMonth == birthMonth); // true && true -> isBday= true
boolean isOver21 = (thisYear-birthYear) >= 21; //2018-1990=28 -> isOver21 = true
boolean canEnter = isBday && isOver21; // canEnter = true && true => true
System.out.println(canEnter);
}
}