Sun Microsystems: Public Class Store
Sun Microsystems: Public Class Store
public class Store {
// instance fields
String productType;
int inventoryCount;
double inventoryPrice;
// constructor method
public Store(String product, int count, double price) {
productType = product;
inventoryCount = count;
inventoryPrice = price;
}
// main method
public static void main(String[] args) {
Store lemonadeStand = new Store("lemonade", 42, .99);
Store cookieShop = new Store("cookies", 12, 3.75);
System.out.println("Our first shop sells " + lemonadeStand.productType + " at " + lemo
nadeStand.inventoryPrice + " per unit.");
System.out.println("Our second shop has " + cookieShop.inventoryCount + " units rem
aining.");
}
}
This is object-oriented programming because programs are built around
objects and their interactions. An object contains state and behavior.
A class is the set of instructions that describe how an instance can behave
and what information it contains.
Classes: Constructors
}
//constructor method ends after curly brace
// program tasks
}
}
public Car() {
}
The declaration is within the class and the instance variable will be
available for assignment inside the constructor.
public class Car {
/*
declare fields inside the class
by specifying the type and name
*/
String color;
public Car() {
/*
instance fields available in
scope of constructor method
*/
}
We’ll use a combination of constructor method and instance field to create instances
with individual state.
Example:
public class Store {
// instance fields
String productType;
// constructor method
public Store(String product) {
productType=product;
}
// main method
public static void main(String[] args) {
}
}
public class Store {
// instance fields
String productType;
// constructor method
public Store(String product) {
productType = product;
}
// main method
public static void main(String[] args) {
Store lemonadeStand= new Store("lemonade");
System.out.println(lemonadeStand.productType);
}
}
lemonade
public class Store {
// instance fields
String productType;
int inventoryCount;
double inventoryPrice;
// constructor method
public Store(String product, int count, double price) {
productType = product;
inventoryCount=count;
inventoryPrice=price;
}
// main method
public static void main(String[] args) {
Store cookieShop=new Store("cookies",12,3.75);
}
}
public class Dog {
String breed;
boolean hasOwner;
int age;
public Dog(String dogBreed, boolean dogOwned, int dogYears) {
System.out.println("Constructor invoked!");
breed = dogBreed;
hasOwner = dogOwned;
age = dogYears;
}
public static void main(String[] args) {
System.out.println("Main method started");
Dog fido = new Dog("poodle", false, 4);
Dog nunzio = new Dog("shiba inu", true, 12);
boolean isFidoOlder = fido.age > nunzio.age;
int totalDogYears = nunzio.age + fido.age;
System.out.println("Two dogs created: a " + fido.breed + " and a "
+ nunzio.breed);
System.out.println("The statement that fido is an older dog is: " +
isFidoOlder);
System.out.println("The total age of the dogs is: " + totalDogYears
);
System.out.println("Main method finished");
}
}
· public means that other classes can access this method. We will learn more about that later in
the course.
· The void keyword means that there is no specific output from the method. We will see
methods that are not void later in this lesson, but for now all of our methods will be void.
· startEngine() is the name of the method
Defining Methods
public class Store {
// instance fields
String productType;
// constructor method
public Store(String product) {
productType = product;
}
// advertise method
public void advertise(){
System.out.println("Come spend some money!");
System.out.println("Selling " + productType + "!");
}
// main method
public static void main(String[] args) {
}
}
Calling Methods
public class Store {
// instance fields
String productType;
// constructor method
public Store(String product) {
productType = product;
}
// advertise method
public void advertise() {
System.out.println("Selling " + productType + "!");
System.out.println("Come spend some money!");
}
// main method
public static void main(String[] args) {
Store lemonadeStand = new Store("Lemonade");
lemonadeStand.advertise();
lemonadeStand.advertise();
lemonadeStand.advertise();
}
}
Selling Lemonade!
Come spend some money!
Selling Lemonade!
Come spend some money!
Selling Lemonade!
Come spend some money!
Everything inside the curly braces is part of the task. This domain
is called the scope of a method
public class Store {
// instance fields
String productType;
// constructor method
public Store(String product) {
productType = product;
}
// advertise method
public void advertise() {
String message = "Selling " + productType + "!";
System.out.println(message);
}
public void greetCustomer(String customer){
System.out.println("Welcome to the store, " + customer + "!");
}
// main method
public static void main(String[] args) {
Store lemonadeStand = new Store("Lemonade");
lemonadeStand.greetCustomer("Laura");
}
}
public class Store {
// instance fields
String productType;
double price;
// constructor method
public Store(String product, double initialPrice) {
productType = product;
price = initialPrice;
}
// increase price method
public void increasePrice(double priceToAdd){
double newPrice=price+priceToAdd;
price=newPrice;
}
// main method
public static void main(String[] args) {
Store lemonadeStand = new Store("Lemonade", 3.75);
lemonadeStand.increasePrice(1.5);
System.out.println(lemonadeStand.price);
}
}
public class Store {
// instance fields
String productType;
double price;
// constructor method
public Store(String product, double initialPrice) {
productType = product;
price = initialPrice;
}
// increase price method
public void increasePrice(double priceToAdd){
double newPrice = price + priceToAdd;
price = newPrice;
}
// get price with tax method
public double getPriceWithTax(){
double totalPrice=price + price * 0.08;
return totalPrice;
}
// main method
public static void main(String[] args) {
Store lemonadeStand = new Store("Lemonade", 3.75);
double lemonadePrice=lemonadeStand.getPriceWithTax();
System.out.println(lemonadePrice);
}
}
public class Store {
// instance fields
String productType;
double price;
// constructor method
public Store(String product, double initialPrice) {
productType = product;
price = initialPrice;
}
// increase price method
public void increasePrice(double priceToAdd){
double newPrice = price + priceToAdd;
price = newPrice;
}
// get price with tax method
public double getPriceWithTax(){
double tax = 0.08;
double totalPrice = price + price*tax;
return totalPrice;
}
public String toString(){
return "This store sells " + productType + " at a price of " + pric
e + ".";
}
// main method
public static void main(String[] args) {
Store lemonadeStand = new Store("Lemonade", 3.75);
Store cookieShop = new Store("Cookies", 5);
System.out.println(lemonadeStand);
System.out.println(cookieShop);
}
}
public class SavingsAccount {
int balance;
public SavingsAccount(int initialBalance){
balance = initialBalance;
}
public void checkBalance(){
System.out.println("Hello!");
System.out.println("Your balance is "+balance);
}
public void deposit(int amountToDeposit){
balance = amountToDeposit + balance;
System.out.println("You just deposited " + amountToDeposit);
}
public int withdraw(int amountToWithdraw){
balance = balance - amountToWithdraw;
System.out.println("You just withdrew " + amountToWithdraw);
return amountToWithdraw;
}
public String toString(){
return "This is a savings account with " + balance + " saved.";
}
public static void main(String[] args){
SavingsAccount savings = new SavingsAccount(2000);
//Check balance:
savings.checkBalance();
//Withdrawing:
savings.withdraw(300);
//Check balance:
savings.checkBalance();
//Deposit:
savings.deposit(600);
//Check balance:
savings.checkBalance();
//Deposit:
savings.deposit(600);
//Check balance:
savings.checkBalance();
System.out.println(savings);
}
}
public class Order {
boolean isFilled;
double billAmount;
String shipping;
public Order(boolean filled, double cost, String shippingMethod) {
if (cost > 24.00) {
System.out.println("High value item!");
}
isFilled = filled;
billAmount = cost;
shipping = shippingMethod;
}
public void ship() {
if (isFilled) {
System.out.println("Shipping");
System.out.println("Shipping cost: " + calculateShipping());
} else {
System.out.println("Order not ready");
}
}
public double calculateShipping() {
// declare conditional statement here
if(shipping=="Regular"){
return 0;
}
else if(shipping=="Express"){
return 1.75;
}
else{
return .50;
}
}
public static void main(String[] args) {
// do not alter the main method!
Order book = new Order(true, 9.99, "Express");
Order chemistrySet = new Order(false, 72.50, "Regular");
book.ship();
chemistrySet.ship();
}
}
public class Order {
boolean isFilled;
double billAmount;
String shipping;
public Order(boolean filled, double cost, String shippingMethod) {
if (cost > 24.00) {
System.out.println("High value item!");
}
isFilled = filled;
billAmount = cost;
shipping = shippingMethod;
}
public void ship() {
if (isFilled) {
System.out.println("Shipping");
System.out.println("Shipping cost: " + calculateShipping());
} else {
System.out.println("Order not ready");
}
}
public double calculateShipping() {
double shippingCost;
// declare switch statement here
switch (shipping) {
case "Regular":
shippingCost = 0;
break;
case "Express":
shippingCost = 1.75;
break;
default:
shippingCost = .50;
}
return shippingCost;
}
public static void main(String[] args) {
// do not alter the main method!
Order book = new Order(true, 9.99, "Express");
Order chemistrySet = new Order(false, 72.50, "Regular");
book.ship();
chemistrySet.ship();
}
}
public class Reservation {
int guestCount;
int restaurantCapacity;
boolean isRestaurantOpen;
boolean isConfirmed;
public Reservation(int count, int capacity, boolean open) {
guestCount = count;
restaurantCapacity = capacity;
isRestaurantOpen = open;
}
public void confirmReservation() {
/*
Write conditional
~~~~~~~~~~~~~~~~~
if restaurantCapacity is greater
or equal to guestCount
AND
the restaurant is open:
print "Reservation confirmed"
set isConfirmed to true
else:
print "Reservation denied"
set isConfirmed to false
*/
if (restaurantCapacity >= guestCount && isRestaurantOpen) {
System.out.println("Reservation confirmed.");
isConfirmed = true;
} else {
System.out.println("Reservation denied.");
isConfirmed = false;
}
}
public void informUser() {
System.out.println("Please enjoy your meal!");
}
public static void main(String[] args) {
Reservation partyOfThree = new Reservation(3, 12, true);
Reservation partyOfFour = new Reservation(4, 3, true);
partyOfThree.confirmReservation();
partyOfThree.informUser();
partyOfFour.confirmReservation();
partyOfFour.informUser();
}
}
public class Reservation {
int guestCount;
int restaurantCapacity;
boolean isRestaurantOpen;
boolean isConfirmed;
public Reservation(int count, int capacity, boolean open) {
if (count < 1 || count > 8) {
System.out.println("Invalid reservation!");
}
guestCount = count;
restaurantCapacity = capacity;
isRestaurantOpen = open;
}
public void confirmReservation() {
if (restaurantCapacity >= guestCount && isRestaurantOpen) {
System.out.println("Reservation confirmed");
isConfirmed = true;
} else {
System.out.println("Reservation denied");
isConfirmed = false;
}
}
public void informUser() {
// Write conditional here
if (!isConfirmed) {
System.out.println("Unable to confirm reservation, please contact
restaurant.");
} else {
System.out.println("Please enjoy your meal!");
}
}
public static void main(String[] args) {
Reservation partyOfThree = new Reservation(3, 12, true);
Reservation partyOfFour = new Reservation(4, 3, true);
partyOfThree.confirmReservation();
partyOfThree.informUser();
partyOfFour.confirmReservation();
partyOfFour.informUser();
}
}
public class Newsfeed {
String[] trendingArticles;
int[] views;
double[] ratings;
public Newsfeed(String[] initialArticles, int[] initialViews, double[
] initialRatings){
trendingArticles = initialArticles;
views = initialViews;
ratings = initialRatings;
}
public String getTopArticle(){
return trendingArticles[0];
}
public void viewArticle(int articleNumber){
views[articleNumber] = views[articleNumber] + 1;
System.out.println("The article '" + trendingArticles[articleNumber
] + "' has now been viewed " + views[articleNumber] + " times!");
}
public void changeRating(int articleNumber, double newRating){
if (newRating > 5 || newRating < 0) {
System.out.println("The rating must be between 0 and 5 stars!");
} else {
ratings[articleNumber] = newRating;
System.out.println("The article '" + trendingArticles[articleNumb
er] + "' is now rated " + ratings[articleNumber] + " stars!");
}
}
public static void main(String[] args){
String[] robotArticles = {"Oil News", "Innovative Motors", "Humans:
Exterminate Or Not?", "Organic Eye Implants", "Path Finding in an Unkno
wn World"};
int[] robotViewers = {87, 32, 13, 11, 7};
double[] robotRatings = {2.5, 3.2, 5.0, 1.7, 4.3};
Newsfeed robotTimes = new Newsfeed(robotArticles, robotViewers, rob
otRatings);
robotTimes.viewArticle(2);
robotTimes.viewArticle(2);
System.out.println("The top article is " + robotTimes.getTopArticle
());
robotTimes.changeRating(3, 5);
}
}
}
public static void main(String[] args){
Newsfeed sampleFeed = new Newsfeed();
String[] topics = sampleFeed.getTopics();
System.out.println(topics);
}
}
import java.util.Arrays;
public class Lottery(){
public class Newsfeed {
public Newsfeed(){
}
public String[] getTopics(){
String[] topics = {"Opinion", "Tech", "Science", "Health"};
return topics;
}
public static void main(String[] args){
Newsfeed sampleFeed = new Newsfeed();
String[] topics = sampleFeed.getTopics();
String betterTopics=Arrays.toString(topics);
System.out.println(betterTopics);
}
}
import java.util.Arrays;
public class Newsfeed {
String[] topics = {"Opinion", "Tech", "Science", "Health"};
int[] views = {0, 0, 0, 0};
public Newsfeed(){
}
public String[] getTopics(){
return topics;
}
public String getTopTopic(){
return topics[0];
}
public void viewTopic(int topicIndex){
views[topicIndex] = views[topicIndex] + 1;
}
public static void main(String[] args){
Newsfeed sampleFeed = new Newsfeed();
System.out.println("The top topic is "+ sampleFeed.getTopTopic());
sampleFeed.viewTopic(1);
sampleFeed.viewTopic(1);
sampleFeed.viewTopic(3);
sampleFeed.viewTopic(2);
sampleFeed.viewTopic(2);
sampleFeed.viewTopic(1);
System.out.println("The " + sampleFeed.topics[1] + " topic has been
viewed " + sampleFeed.views[1] + " times!");
}
}
import java.util.Arrays;
public class Newsfeed {
String[] topics = {"Opinion", "Tech", "Science", "Health"};
int[] views = {0, 0, 0, 0};
String[] favoriteArticles;
public Newsfeed(){
favoriteArticles = new String[10];
}
public void setFavoriteArticle(int favoriteIndex, String newArticle){
favoriteArticles[favoriteIndex] = newArticle;
}
public static void main(String[] args){
Newsfeed sampleFeed = new Newsfeed();
sampleFeed.setFavoriteArticle(2, "Humans: Exterminate Or Not?");
sampleFeed.setFavoriteArticle(3, "Organic Eye Implants");
sampleFeed.setFavoriteArticle(0, "Oil News");
System.out.println(Arrays.toString(sampleFeed.favoriteArticles));
}
}
Return length:
import java.util.Arrays;
public class Newsfeed {
String[] topics = {"Opinion", "Tech", "Science", "Health"};
int[] views = {0, 0, 0, 0};
public Newsfeed(){
}
public String[] getTopics(){
return topics;
}
public int getNumTopics(){
return topics.length;
}
public static void main(String[] args){
Newsfeed sampleFeed = new Newsfeed();
System.out.println("The number of topics is "+ sampleFeed.getNumTop
ics());
}
}
Remember that to run programs from the command line, we use syntax like:
Remember that to run programs from the command line, we use syntax like:
public class Newsfeed {
String[] topics;
public Newsfeed(String[] initialTopics) {
topics = initialTopics;
}
public static void main(String[] args) {
Newsfeed feed;
if (args[0].equals("Human")) {
//topics for a Human feed:
String[] humanTopics = {"Politics", "Science", "Sports", "Love"};
feed = new Newsfeed(humanTopics);
} else if(args[0].equals("Robot")) {
//topics for a Robot feed:
String[] robotTopics = {"Oil", "Parts", "Algorithms", "Love"};
feed = new Newsfeed(robotTopics);
} else {
String[] genericTopics = {"Opinion", "Tech", "Science", "Health"}
;
feed = new Newsfeed(genericTopics);
}
System.out.println("The topics in this feed are:");
System.out.println(Arrays.toString(feed.topics));
}
}
/ import the ArrayList package here:
import java.util.ArrayList;
class ToDos {
public static void main(String[] args) {
// Create toDoList below:
// ArrayList<String> toDoList;
ArrayList<String> toDoList=new ArrayList<String>();
}
}
import java.util.ArrayList;
class ToDos {
public static void main(String[] args) {
// Sherlock
ArrayList<String> sherlocksToDos = new ArrayList<String>();
sherlocksToDos.add("visit the crime scene");
sherlocksToDos.add("play violin");
sherlocksToDos.add("interview suspects");
sherlocksToDos.add("solve the case");
sherlocksToDos.add("apprehend the criminal");
// Poirot
ArrayList<String> poirotsToDos = new ArrayList<String>();
poirotsToDos.add("visit the crime scene");
poirotsToDos.add("interview suspects");
poirotsToDos.add("let the little grey cells do their work");
poirotsToDos.add("trim mustache");
poirotsToDos.add("call all suspects together");
poirotsToDos.add("reveal the truth of the crime");
System.out.println("Sherlock's third to-do:");
// Print Sherlock's third to-do:
System.out.println(sherlocksToDos.get(2));
System.out.println("\nPoirot's second to-do:");
// Print Poirot's second to-do:
System.out.println(poirotsToDos.get(1));
}
}
Set()
import java.util.ArrayList;
class ToDos {
public static void main(String[] args) {
// Sherlock
ArrayList<String> sherlocksToDos = new ArrayList<String>();
sherlocksToDos.add("visit the crime scene");
sherlocksToDos.add("play violin");
sherlocksToDos.add("interview suspects");
sherlocksToDos.add("solve the case");
sherlocksToDos.add("apprehend the criminal");
sherlocksToDos.set(1,"listen to Dr. Watson for amusement");
// Poirot
ArrayList<String> poirotsToDos = new ArrayList<String>();
poirotsToDos.add("visit the crime scene");
poirotsToDos.add("interview suspects");
poirotsToDos.add("let the little grey cells do their work");
poirotsToDos.add("trim mustache");
poirotsToDos.add("call all suspects together");
poirotsToDos.add("reveal the truth of the crime");
// Set each to-do below:
poirotsToDos.set(3, "listen to Captain Hastings for amusement");
System.out.println("Sherlock's to-do list:");
System.out.println(sherlocksToDos.toString() + "\n");
System.out.println("Poirot's to-do list:");
System.out.println(poirotsToDos.toString());
}
}
shoppingCart.remove("Trench Coat");
System.out.println(detectives.indexOf("Fletcher"));
import java.util.ArrayList;
class ToDos {
public static void main(String[] args) {
// Sherlock
ArrayList<String> sherlocksToDos = new ArrayList<String>();
sherlocksToDos.add("visit the crime scene");
sherlocksToDos.add("play violin");
sherlocksToDos.add("interview suspects");
sherlocksToDos.add("listen to Dr. Watson for amusement");
sherlocksToDos.add("solve the case");
sherlocksToDos.add("apprehend the criminal");
sherlocksToDos.remove("visit the crime scene");
// Calculate to-dos until case is solved:
int solved = sherlocksToDos.indexOf("solve the case");
// Change the value printed:
System.out.println(solved);
}
}
While loop
import java.util.Random;
class LuckyFive {
public static void main(String[] args) {
// Creating a random number generator
Random randomGenerator = new Random();
// Generate a number between 1 and 6
int dieRoll = randomGenerator.nextInt(6) + 1;
// Repeat while roll isn't 5
while (dieRoll != 5) {
System.out.println(dieRoll);
dieRoll = randomGenerator.nextInt(6) + 1;
}
}
}
import java.util.ArrayList;
class CalculateTotal {
public static void main(String[] args) {
ArrayList<Double> expenses = new ArrayList<Double>();
expenses.add(74.46);
expenses.add(63.99);
expenses.add(10.57);
expenses.add(81.37);
double total = 0;
// Iterate over expenses
for(int i=0;i<expenses.size();i++){
total=total+expenses.get(i);
}
System.out.println(total);
}
}
import java.util.ArrayList;
class MostExpensive {
public static void main(String[] args) {
ArrayList<Double> expenses = new ArrayList<Double>();
expenses.add(74.46);
expenses.add(63.99);
expenses.add(10.57);
expenses.add(81.37);
double mostExpensive = 0;
// Iterate over expenses
for (double expense : expenses) {
if (expense > mostExpensive) {
mostExpensive = expense;
}
}
System.out.println(mostExpensive);
}
}
For-each loops: These make it simple to do something with each item in a list. For example:
STRING:
public class HelloWorld {
public static void main(String[] args) {
String str = "Hello, World!";
// Examples:
System.out.println(str.length());
System.out.println(str.substring(4));
System.out.println(str.toUpperCase());
}
}
Concat:
String firstName = "Ziggy"; String lastName = "Stardust";
System.out.println(firstName.concat(" " + lastName));
System.out.println(firstName.charAt(0));
System.out.println(lastName.charAt(0));
class Noodle {
double lengthInCentimeters;
double widthInCentimeters;
String shape;
String ingredients;
String texture = "brittle";
Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
this.lengthInCentimeters = lenInCent;
this.widthInCentimeters = wthInCent;
this.shape = shp;
this.ingredients = ingr;
}
public void cook() {
this.texture = "cooked";
}
public static void main(String[] args) {
Pho phoChay=new Pho();
System.out.println(phoChay.shape);
}
}
ublic class Noodle {
private double lengthInCentimeters;
private double widthInCentimeters;
private String shape;
protected String ingredients;
private String texture = "brittle";
Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
this.lengthInCentimeters = lenInCent;
this.widthInCentimeters = wthInCent;
this.shape = shp;
this.ingredients = ingr;
}
final public boolean isTasty() {
return true;
}
public static void main(String[] args) {
Ramen yasaiRamen = new Ramen();
System.out.println(yasaiRamen.ingredients);
System.out.println(yasaiRamen.isTasty());
}
}
Polymorphism, which derives from Greek meaning “many forms”, allows a child class
to share the information and behavior of its parent class while also incorporating its
own functionality.
These benefits are particularly helpful when we want to develop our own Java
packages for other developers to import and use.
class Noodle {
protected double lengthInCentimeters;
protected double widthInCentimeters;
protected String shape;
protected String ingredients;
protected String texture = "brittle";
Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
this.lengthInCentimeters = lenInCent;
this.widthInCentimeters = wthInCent;
this.shape = shp;
this.ingredients = ingr;
}
public void cook() {
System.out.println("Boiling.");
this.texture = "cooked";
}
public static void main(String[] args) {
Spaetzle kaesespaetzle = new Spaetzle();
kaesespaetzle.cook();
}
}
class Spaetzle extends Noodle {
Spaetzle() {
super(3.0, 1.5, "irregular", "eggs, flour, salt");
this.texture = "lumpy and liquid";
}
// Add the new cook() method below:
@Override
public void cook() {
System.out.println("Grinding or scraping dough.");
System.out.println("Boiling.");
this.texture = "cooked";
}
}
class Dinner {
private void makeNoodles(Noodle noodle, String sauce) {
noodle.cook();
System.out.println("Mixing " + noodle.texture + " noodles made from
" + noodle.ingredients + " with " + sauce + ".");
System.out.println("Dinner is served!");
}
public static void main(String[] args) {
Dinner noodlesDinner = new Dinner();
// Add your code here:
Noodle biangBiang = new BiangBiang();
noodlesDinner.makeNoodles(biangBiang, "soy sauce and chili oil");
}
}
class Noodle {
protected double lengthInCentimeters;
protected double widthInCentimeters;
protected String shape;
protected String ingredients;
protected String texture = "brittle";
Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
this.lengthInCentimeters = lenInCent;
this.widthInCentimeters = wthInCent;
this.shape = shp;
this.ingredients = ingr;
}
public void cook() {
this.texture = "cooked";
}
}
class BiangBiang extends Noodle {
BiangBiang() {
super(50.0, 5.0, "flat", "high-gluten flour, salt, water");
}
}
System.out.println(monster.attack());
}
· A Java class can inherit fields and methods from another class.
· Each Java class requires its own file, but only one class in a Java package needs a main()
method.
· Child classes inherit the parent constructor by default, but it’s possible to modify the constructor
using super() or override it completely.
· You can use protected and final to control child class access to parent class members.
· Java’s OOP principle of polymorphism means you can use a child class object like a member of its
parent class, but also give it its own traits.
· You can override parent class methods in the child class, ideally using the @Override keyword.
· It’s possible to use objects of different classes that share a parent class together in an array or
ArrayList
Syntax errors: Errors found by the compiler.
Run-time errors: Errors that occur when the program is running.
Logic errors: Errors found by the programmer looking for the causes of erroneous results.
Exceptions are the conditions that occur at runtime and may cause the
termination of the program.
When an exception occurs, Java displays a message that includes the name of the
exception, the line of the program where the exception occurred, and a stack trace.
The stack trace includes:
The try statement allows you to define a block of code to be tested for
errors while it is being executed.
try {
} catch (NullPointerException e) {
public class Debug {
public static void main(String[] args) {
try{
int width = 0;
int length = 40;
int ratio = length / width;
}catch(ArithmeticException e){
System.err.println("ArithmeticException: " + e.getMessage());
}
}
}
ArithmeticException: / by zero
import java.util.*;
public class AreaCalculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Shape Area Calculator");
while(true) {
System.out.println();
System.out.println("-=-=-=-=-=-=-=-=-=-");
System.out.println();
System.out.println("1) Triangle");
System.out.println("2) Rectangle");
System.out.println("3) Circle");
System.out.println("4) Quit");
System.out.println();
System.out.print("Which shape: ");
int shape = keyboard.nextInt();
System.out.println();
if (shape == 1) {
area_triangle(5,6);
} else if (shape == 2) {
area_rectangle(4,5);
} else if (shape == 3) {
area_circle(4);
} else if (shape == 4) {
quit();
break;
}
}
}
public static double area_triangle(int base, int height) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Base: ");
base = keyboard.nextInt();
System.out.print("Height: ");
height = keyboard.nextInt();
System.out.println();
int A = (base * height) * 2;
System.out.println("The area is " + A + ".");
return A;
}
public static int area_rectangle(int length, int width){
Scanner keyboard = new Scanner(System.in);
System.out.print("Length: ");
length = keyboard.nextInt();
System.out.print("Width: ");
width = keyboard.nextInt();
System.out.println();
int A = length * width;
System.out.println("The area is " + A + ".");
return A;
}
public static double area_circle(int radius) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Radius: ");
radius = keyboard.nextInt();
System.out.println();
double A = Math.PI * radius * radius;
System.out.println("The area is " + A + ".");
return A;
}
public static String quit() {
System.out.println("GoodBye");
return null;
}
}